Dockerized nginx is not starting

Solution 1:

As of now, the official nginx image uses this to run nginx (see the Dockerfile):

CMD ["nginx", "-g", "daemon off;"]

In my case, this was enough to get it to start properly. There are tutorials online suggesting more awkward ways of accomplishing this but the above seems quite clean.

Solution 2:

Docker container runs as long as the command you specify with CMD, ENTRTYPOINT or through the command line is running. In your case the service command finishes right away and the whole container is shut down.

One way to fix this is to start nginx directly from the command line (make sure you don't run it as a daemon).

Another option is to create a small script which starts the service and then sleeps forever. Something like:

#!/bin/bash
service nginx start
while true; do sleep 1d; done

and run this instead of directly running the service command.

A third option would be to use something like runit or similar program, instead of the normal service.

Solution 3:

Using docker-compose:

To follow the recommended solution, add to docker-compose.yml:

command: nginx -g "daemon off"

I also found I could simply add to nginx.conf:

daemon off;

...and continue to use in docker-compose.yml:

command: service nginx start

...although it would make the config file less portable outside docker.

Solution 4:

Docker as a very nice index of offical and user images. When you want to do something, chances are someone already did it ;)

Just search for 'nginx' on index.docker.io, you will see, there is an official nginx image: https://registry.hub.docker.com/_/nginx/

There you have a full guide to help you start your webserver.

Feel free to take a look at other users nginx image to see variants :)

The idea is to start nginx in foreground mode.