Docker port mapping, rename container, restart the container, exec container

Port mapping

Port mapping is used to map the container port to our machine port. Say you have started a container which is a web application. How can you view that application on your local system? We cannot directly view the web application on the local system we have to do a port mapping for that.

We have to use “-p” to do the mapping.

Firstly we will start the Nginx container without port mapping and see the results.

Note*Nginx is a web application

>> docker container run -d –name webserver nginx

-d : helps to run the container in background
— name : specifies the name of the container

We will trigger the “ipconfig” command to get the IP address of our machine.

>> ipconfig

Output : 176.218.148.1

Now the Nginx container is up, we will try to access Nginx container from the local system. We will try to access it using our system IP. We cannot access it as our local system is not aware of the Nginx container.

Now we will do a port mapping for the Nginx container.

>> docker container run -d -p 8000:80 –name webserver-1 nginx

-p : It is used to do the port mapping from container to local system

80 is the port number of container, 8000 is the port number of the local system
Here 80 is mapped to 8000. Now we can access the Nginx container on local system using 8000 port.

Now whenever a request comes to “176.218.148.1:8000” which is our local system IP and port, the request gets delegated to the “webserver-1” container with 80 port as mapping is already done.

Rename the container

We have started an Nginx container with name as “webserver-1”. If we have to change the name of the container then we have to use the rename command.

>> docker container rename CONTAINER-ID new-name

rename : It is use to rename the container

>> docker container rename c497c14a8f23 webserver-101

Restart the container

As the name describes it is used to restart the container.

>> docker container restart CONTAINER-ID

restart : It is use to restart the container

Note* We can check the time to see if the container is restarted.

Exec command

This command is used to run a command inside a running container. If you have to go inside a container you can make use of the below command.

>> docker container exec -it CONTAINER-ID /bin/bash

/bin/bash is the command which is ran inside the container

In this article, we have covered docker container commands for port mapping, renaming the container, restarting the container, and executing the commands inside the running container along with examples. I hope you found this article interesting and valuable. Please share this article with your friends and help me grow. If you are having any concerns or questions about this article please comment below. If you want to get in touch with me please visit the Contact Me page and send me an email.

Leave a Comment