Tuesday 5 December 2023

Edit, add, or remove ports of an existing Docker container

In some cases you need to assign additional ports to a running Docker container, or change the ports in use. This is completely possible without creating a new docker image or re-running docker run to create a new container. To change the ports of a running Docker Container, follow the instructions below.

Example: we have a container of image php:8.1-apache configured with port mapping 8080->80/tcp. We will edit this container to open port 8081->443/tcp.

Warning! You should back up before editing any files

Step 1: Go to your container configuration directory

Go to the directory where the containers are stored

cd /var/lib/docker/containers

Here you will see folders with names corresponding to container ids. Then access the directory of the corresponding container you need to edit.

The full path will be as follows


You can find the container's hash id via the command

docker ps -a

Step 2: Stop docker service (docker.socket)

systemctl stop docker.socket

Step 3: Edit expose ports config in file config.v2.json

We will declare port 443 on the container

Find json string 


Then add new port


Step 4: Edit ports mapping config in file hostconfig.json

We will map port 8081 on the host computer to the newly created port 443/tcp on the container

Find json string 


Then add new port


Step 5: Restart the docker service

systemctl start docker

Done !