Ways to Assign a New Port Mapping To A Running Container
There are a few ways to assign a new port mapping to a running container in Docker:
1. Stop And Restart The Container
We can Stop the running Container with the docker command “docker stop” and again run the container with the command “docker run” While running the container again use the below command.
docker run -p <HostPort:containerport> imagename:tag
2. Update The Running Container
If you wish to update the port mapping of a container named my container to map port 8080 on the host to port 80 on the container using the command, for instance, you can map the container port to the host port by updating the container.
docker container update --publish-add 8080:80 my_container
3. Using the Docker API
Additionally, you can alter a running container’s port mapping using the Docker API. Sending a POST request with the new port mapping configuration in the request body to the /containers/(id)/update endpoint will do this.
Example: You can send a POST request to http://localhost/containers/(container_id)/update with a JSON payload containing the new port mapping configuration.
4. Update Config Files To Change The Container Port In The Docker
- By using “docker ps” list all the containers and pick the container from the list to which the container port is to be changed.
- Stop the container to which you need to change the ports by using “docker stop”
- Find the port mapping definitions section of the configuration file. Typically, this section will have a queue like ports: – [HOST PORT]:[CONTAINER PORT]. The new port number you want to use should be entered as the value for “CONTAINER PORT”. In the configuration file, save the modifications.
- Use the docker start command with the container name or ID to restart the container. By using “docker start”
How to Map Ports in Docker?
In docker, all the application in the container runs on particular ports when you run a container. If you want to access the particular application with the help of a port number you need to map the port number of the container with the port number of the docker host.