Run nginx in docker container

Docker can be used to run nginx in a container. We’ll use Ubuntu Linux (14.04.2) for the purpose of this tutorial. This tutorial assumes that you have installed docker on your Ubuntu machine.

  1. Download latest nginx image

    $ docker pull nginx
    Using default tag: latest
    latest: Pulling from library/nginx
    Status: Downloaded newer image for nginx:latest
  2. Run nginx server with name nginx1 and port 8081 mapped to contaner port 80.

    $ docker run --name nginx1 -p 8081:80 -d  nginx
    docker ps
    CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                           NAMES
    e301d1d599f0        nginx               "nginx -g 'daemon off"   2 seconds ago       Up 2 seconds        443/tcp,>80/tcp   nginx1
  3. Check if nginx is listening on port 8081.
    $ curl http://localhost:8081/
    <!DOCTYPE html>
    <title>Welcome to nginx!</title>
        body {
            width: 35em;
            margin: 0 auto;
            font-family: Tahoma, Verdana, Arial, sans-serif;
    <h1>Welcome to nginx!</h1>
    <p>If you see this page, the nginx web server is successfully installed and
    working. Further configuration is required.</p>
    <p>For online documentation and support please refer to
    <a href=""></a>.<br/>
    Commercial support is available at
    <a href=""></a>.</p>
    <p><em>Thank you for using nginx.</em></p>
  4. Link nginx document root to local directory.
    $ sudo mkdir -p /opt/tmp/nginx1/html
    $ sudo bash -c 'echo "foo" > /opt/tmp/nginx1/html/index.html'
    ## in case old container is running
    $ docker kill nginx1
    $ docker rm nginx1
    $ docker run --name nginx1 -p 8081:80 -d -v /opt/tmp/nginx1/log:/var/log/nginx  -v /opt/tmp/nginx1/html:/usr/share/nginx/html nginx
    $ curl http://localhost:8081/
    $ cat /opt/tmp/nginx1/log/access.log - - [05/Feb/2016:05:05:41 +0000] "GET / HTTP/1.1" 200 4 "-" "curl/7.35.0" "-"
  5. Get an interactive bash shell in running nginx container
    $ docker exec -it nginx1 /bin/bash
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments