To assign a port mapping to an existing Docker container, you’ll need to follow these steps:
1. Stop the running container: First, stop the container using the command:
docker stop <container_name_or_id>
2. Commit the container to a new image: Create a new image from the current state of the container. This will preserve any changes you’ve made to the container:
docker commit <container_name_or_id> <new_image_name>
3. Delete the old container: Now, remove the old container. Your changes are saved in the new image, so you won’t lose any data:
docker rm <container_name_or_id>
4.Create a new container with the desired port mapping: Use the new image to create a new container with the port mapping you want:
docker run -d --name <new_container_name> -p <host_port>:<container_port> <new_image_name>
Replace <host_port>
with the port number on the host, and <container_port>
with the port number inside the container that you want to expose.
5. Start the new container: Finally, start the new container with the command:
docker start <new_container_name>
Make sure to replace <container_name_or_id>
, <new_container_name>
, <new_image_name>
, <host_port>
, and <container_port>
with the actual names, IDs, and port numbers relevant to your Docker setup.