Nginx in a Docker

Written by:

Docker provides a level of isolation between applications, as each container runs its own set of processes and does not interfere with other containers. This isolation simplifies dependency management and enhances security.

Today I will show a simple example of how to run Nginx in a docker instead of installing it directly on the Server. I will use a Linux CentOS 7 in this example.

1 – Installation of the docker.

yum install -y yum-utils
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
yum install -y docker-ce docker-ce-cli containerd.io

2 – Start the docker and enable it to start on the startup.

systemctl start docker && systemctl enable docker

3 – To check the docker version running.

docker version

4 – Pull the Nginx docker image.

docker pull nginx

5 – Run the Nginx container using the pulled image and confirm the container is running. You can give it any name you wish.

docker run -d -p 80:80 --name your-container-name nginx
docker ps

You can see the description of the options used above:

-d: Runs the container in detached mode (background).
-p 80:80: Maps port 80 on the host to port 80 on the container.
–name nginx-willian: Name of the container.

6 – To verify the Nginx’s functionality, open a browser and enter the Linux machine’s IP address or hostname. The default Nginx page should appear as below.

7 –  To check the logs related to your container

–follow or -f: Follow log output (real-time, similar to tail -f).
–since: Show logs since a certain time (e.g., –since 1h30m for logs in the last 1 hour and 30 minutes).
–tail: Number of lines to show from the end of the logs (e.g., –tail 100).

docker logs your-container-name

10 – To edit the “home page” (index.html) of your nginx, you can follow the below.

docker exec -it nginx-willian exec
echo "Nginx WillianIT Docker" >> /usr/share/nginx/html/index.html

NOTE: If you want to replace everything of index.html page instead, use only 1 “>”. (e.g. echo “nginx Test 01” > /usr/share/nginx/html/index.html

11 – Refresh the page, you will see the changes made.

cd /etc/nginx/conf.d touch default.conf

12 – To see containers not in use:

docker ps -a

13 – To see all the docker images in place

docker images

14 – To stop the nginx container and remove it

docker stop your-container-name
docker rm your-container-name

To check more options related to Nginx docker, check the docker documentation.

Leave a Reply

Your email address will not be published. Required fields are marked *