Getting a container that has preinstalled Nginx has two benefits:
- It is easy to ship containers.
- We can destroy and recreate the containers any number of times.
To get the latest Nginx image and start a container, run the following command:
> docker run --name nginxServer -d -p 80:80 nginx
This pulls the nginx image from Docker Hub (make sure you are connected to the internet). If the image is already pulled, it reuses that. Then, it starts a container with the name of nginxServer and serves it on port 80. Now, visit http://localhost from your browser and you will see the Nginx home page.
However, the preceding command is not useful for configuring Nginx after starting the container. We have to mount a directory from localhost to the container or copy files to the container to make changes to the Nginx configuration file. Let's modify the command:
> docker run --name nginxServer -d -p 80:80 --mount source=/host/path/nginx.conf,destination=/etc/nginx/nginx.conf:readonly nginx
The extra command is --mount, which mounts a file/directory from the source (host) to the destination (container). If you modify a file on the host system in that directory, then it also reflects on the container. The readonly option stops users/system processes modifying the Nginx configuration inside the container.
In the preceding command, we are mounting the Nginx configuration file, nginx.conf. We use the Docker container-based deployment in the latter part of this chapter, where we use docker-compose to deploy our application.