When docker Run creates and runs containers, port mapping rules can be specified with -p. However, chances are you forgot to set them in the first place, or set them wrong and need to change them.

The Docker start runtime container does not provide a -p option that lets you specify port mapping rules. One solution is to delete the original container and build a new one.

If a stateless application mirror is fine, if a database mirror is a nightmare 🙂

Here are a few solutions:

Method 1: Modify the image configuration file and restart the Docker

The configuration file for the container is in

/var/lib/docker/containers/[hash_of_the_container]/hostconfig.json
Copy the code

Hash_of_the_container is the hash value of the docker image, which can be viewed using docker ps or docker inspect Container_name.

For example, in this example, 5432/ TCP corresponds to 5432 port inside the container, and HostPort corresponds to the port that is mapped to the host. You can change this number. Then restart the Docker service:

systemctl restart docker
Copy the code

Finally start docker image.

The advantage of this method is that there are no side effects and the operation is very simple. The disadvantage is that the whole Docker service needs to be restarted. If many images are running on the same host, the services of other containers may be affected.

Method 2: Use docker Commit

Step 1: Stop the Docker container

docker stop container01
Copy the code

Step 2: Commit the Docker container

docker commit container01 new_image:tag
Copy the code

Docker commit: Commit a container’s file changes and configuration information to a new image. This can be useful when testing, importing all of the container’s file changes into a new Dockers image, and then using this image to create a container that has no effect on the previous container. Note that:

Step 3: Create a new container with the image created in the previous step

docker run --name container02 -p 80:80 new_image:tag
Copy the code

The advantage of this approach is that it does not affect other containers on the unified host, but the disadvantage is that it is messy to manage and not as straightforward as the first approach.

I generally prefer the first approach, but only the second if I can’t affect other services on the unified host.

Follow my wechat official account