乐闻世界logo
搜索文章和话题

How do I assign a port mapping to an existing Docker container?

1个答案

1

To configure port mapping for an existing Docker container, follow these steps. Note that directly modifying port mappings on a running container is not supported; instead, use an indirect approach.

Step 1: Stop the current running container

First, stop the currently running container. Use the following command:

bash
docker stop container ID or name

Step 2: Remove the current container

Since Docker does not support directly modifying port mappings on running containers, remove the current container. Use the following command:

bash
docker rm container ID or name

Step 3: Recreate and start the container with new port mapping

Recreate and start the container using the original configuration and new port mapping parameters. For example, to map the container's internal port 80 to the host's port 8080, use:

bash
docker run -p 8080:80 --name container name -other options image name

Here, -p 8080:80 specifies the new port mapping.

Example

Assume you have a container named my-web-app running a web service, originally accessible only on the container's internal port 80. Now, to allow external access through the host's port 8080, follow these steps:

  1. Stop the container:
    bash

docker stop my-web-app

shell
2. Remove the container: ```bash docker rm my-web-app
  1. Recreate and start the container with port mapping:
    bash

docker run -p 8080:80 --name my-web-app your-image-name

shell
By using this method, you can reconfigure port mapping for existing Docker containers. However, remember to back up important data within the container, as removing the container may result in data loss unless you have used volumes or other persistent data strategies.
2024年8月10日 00:40 回复

你的答案