Nginx with Docker Container [Production Ready]

Nginx with Docker Container [Production Ready]

NGINX is a web server which accelerates content and application delivery, improves security, facilitates availability and scalability for the busiest websites on the Internet. Deploying nginx in docker is more comfortable and very easy to manage.

Deploying Nginx Docker

In docker hub, we can find the latest tag build which is build on Debian based image and also there is another variant called alpine which is build on alpine base image. So we can use any variant, but I recommend latest/mainline variant for production.

Using this command, we can pull the docker image and start running the container.

docker run --name nginx-sample -p8080:80 -d nginx:latest

Open the page http://localhost:8080 in your browser to get nginx sample page.

Mounting Directories

The sample nginx container is working fine. But for the content and the configuration, access is possible only inside the container. Also, it’s ephemeral volume, so we have to mount the volumes for static use.

docker run --name nginx -p80:80 -v ~/nginx/html:/usr/share/nginx/html -v ~/nginx/etc:/etc/nginx -d nginx:latest

This should get failed if No config file is present under ~/nginx/etc. So pls create configuration file first. If not, then run this command to copy from the nginx sample container.

docker cp nginx-sample:/etc/nginx ~/nginx/etc

Now. We can rerun the nginx container with mounted config files and static files. So your data will never lose even after recreate the container.

Important Arguments

Here, some important container arguments when we run the docker container. Which is very useful in the production.

docker run --name nginx --net=host -v ~/nginx/html:/usr/share/nginx/html -v ~/nginx/etc:/etc/nginx --restart always -d nginx:latest

–net=host This argument is used to bind the main network interface instead of binding the docker virtual interface. Will speed up the connection.

–restart always This argument is used to restart the container if it went down due to process killed/ crashed. So it’s safe to use when in production.

Wrap Up

Nginx is very lightweight and fastest web server. And We can add more power with the help of the docker container. This tutorial is mainly focused for the beginners who started the hobby project / WordPress in single machines.

If Cloudflare in front of nginx container then SSL is not need but if not then you can refer this Link to set up Free SSL for NGINX docker container with auto-renewal.

Leave a Reply

Your email address will not be published.