To assign a port mapping to an existing Docker container, you can follow these steps:
Identify the Container: Find the container ID or name of the Docker container you want to modify. You can use the
docker pscommand to list all running containers:Stop the Container (if it's running): If the container is running, stop it using the following command. Replace
CONTAINER_IDwith the actual ID or name of your container:Remove the Existing Container (if necessary): If you prefer to keep the existing container's data, you can skip this step. However, if you want to start a new container based on the same image but with a different port mapping, you might need to remove the existing container. Be careful as removing a container deletes any changes made inside the container:
Create a New Container with the Desired Port Mapping: You can create a new container based on the existing container's image and define the port mapping at this stage. Use the
pflag to map the ports:
NEW_HOST_PORT: This is the port on the host machine where you want to map the container's port.EXISTING_CONTAINER_PORT: This is the port inside the container that you want to expose.NEW_CONTAINER_NAME: This is the name you want to assign to the new container.IMAGE_NAME: This is the image of the existing container.
Start the New Container: Once you've created the new container with the modified port mapping, start it:
Remember to replace the placeholder values (like NEW_HOST_PORT, EXISTING_CONTAINER_PORT, NEW_CONTAINER_NAME, and IMAGE_NAME) with your actual port numbers, container name, and image name.
By following these steps, you can re-create a container based on an existing image with a different port mapping. This allows you to assign a new port to an existing Docker container without directly modifying the port mappings of a running container.
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.