Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

docker custom nginx container failed to start

Tags:

docker

nginx

I am trying to build a nginx image from scratch (instead of using the official nginx image)

FROM ubuntu
RUN apt-get update
RUN apt-get install -y nginx    
RUN rm -v /etc/nginx/nginx.conf
ADD nginx.conf /etc/nginx/
RUN echo "daemon off;" >> /etc/nginx/nginx.conf

EXPOSE 80

COPY ./files/ /var/www/html/

CMD service nginx start

And this is my nginx.conf file under current directory.

server {

    root /var/www/html

    location / {
        index.html
    }

}

And my dummy index.html file under ./files folder

<p1>hello world</p1>

I run this command

docker build -t hello-world .

And

docker run -p 80:80 hello-world

But I got error saying

 * Starting nginx nginx
   ...fail!

What maybe the issue?

like image 775
OMGPOP Avatar asked Feb 18 '17 19:02

OMGPOP


2 Answers

Don't use "service xyz start"

To run a server inside a container, don't use the service command. That is a script which will run the requested server in the background, and then exit. When the script exits, the container will stop (because that script was the primary process).

Instead, directly run the command that the service script would have started for you. Unless it exits or crashes, the container should remain running.

CMD ["/usr/sbin/nginx"]

nginx.conf is missing the events section

This is required. Something like:

events {
    worker_connections 1024;
}

The server directive is not a top-level element

You have server { } at the top level of the nginx.conf, but it has to be inside a protocol definition such as http { } to be valid.

http {
    server {
        ...

nginx directives end with a semicolon

These are missing at the end of the root statement and your index.html line.

Missing the "index" directive

To define the index file, use index, not just the filename by itself.

index index.html;

There is no HTML element "p1"

I assume you meant to use <p> here.

<p>hello world</p>

Final result

Dockerfile:

FROM ubuntu
RUN apt-get update
RUN apt-get install -y nginx
RUN rm -v /etc/nginx/nginx.conf
ADD nginx.conf /etc/nginx/
RUN echo "daemon off;" >> /etc/nginx/nginx.conf

EXPOSE 80

COPY ./files/ /var/www/html/

CMD ["/usr/sbin/nginx"]

nginx.conf:

http {
    server {

        root /var/www/html;

        location / {
            index index.html;
        }
    }
}
events {
    worker_connections 1024;
}
daemon off;
like image 166
Dan Lowe Avatar answered Sep 29 '22 10:09

Dan Lowe


one can use directly the official image of nginx in docker hub, just start your docker file with this line : FROM nginx

here is an example of docker file that you can use :

FROM nginx
COPY nginx.conf /etc/nginx/nginx.conf
COPY static-html-directory /usr/share/nginx/html
EXPOSE 80

as you see there is no need to use a CMD to run your nginx server

like image 24
Hamza Hanafi Avatar answered Sep 29 '22 11:09

Hamza Hanafi