Nginx on Docker
In this article , we are going to demonstrate how we can run one of the most commonly used , simple to set up and high performing web server in a docker container.
Pre Requisites
Just Docker Desktop and command line — which you already have on your system :)
Step 1 : Pre setup steps
- Open your command line , in our case I’ll be using windows PowerShell.
- Ensure docker is running fine on your system by running the below command.
docker --version
If this command gives you the version of docker as output, you should consider its running fine.
Step 2: Pulling nginx image from docker hub
- Run the below command to start a new docker container , which will be running nginx web server.
docker run -d --name mickey nginx
This docker run command will pull official nginx image from docker hub , if it is not able to find it from your local system. Docker will then start a container named “mickey” which will be running nginx web server.
-d flag is for ensuring that this process is running in the background.
- once you run the above command , you will see some random characters , that is your unique container id.
- Verify that container is running using the docker ps command:
docker ps -a
By default nginx container listens on port 80.
You can also see your container running in docker desktop:
Step 3: Accessing the nginx web server
Since your web server is running inside the container, if you log in to your container , you should be able to interact with it.
Login to container using below command:
docker exec -it mickey bash
Now you are inside nginx web server , try hitting localhost and you should see something like this:
This validates that you are able to access the web server “locally”. Locally inside your container , not your own host machine.
At the moment if you hit localhost on your system’s web browser , you will not be able to access this web server for obvious reasons.
By default, Nginx container is listening on port 80. If you want to access it from outside the container, say , from your host machine, you need to map the container’s port 80 to a port on your host machine (port 8888 in our case). This can be done by running below command:
docker run -d -p 8888:80 --name mickey nginx
Make sure , you delete the old docker container named “mickey” before running the above command, else you will get error due to naming conflict. You can use following command for same : docker rm <container_id_or_name>
Now if you hit http://localhost:8888 on your host browser you should be able to access it:
This completes our simple demo of running nginx web server on a docker container and accessing it from outside the container.
In next article we will be talking about how to do volume mounting for syncing file from local directory to the nginx container.
Cheers !