How to Add or Modify Docker Container Port Mappings After Creation
This guide explains step‑by‑step how to add, change, or remove port mappings for Docker containers by stopping the container, editing hostconfig.json (and optionally config.v2.json), and restarting the container, with commands for both Linux and Docker Desktop for Mac.
Reading font

If a container hasn't been built yet, you can add port mappings during creation by using multiple -p options in the docker run command, for example:
docker run --name api_dfo_hyperf_ws \
-v /Users/pudongping/glory/codes/dfo/api_dfo_hyperf:/api_dfo_hyperf \
-p 9502:9502 \
-p 9503:9503 \
-p 9504:9504 \
-p 9505:9505 \
-it \
--entrypoint /bin/sh \
alex/alex_api_dfo:v1.0To modify or add ports on an already running container, first stop it: docker stop <container_id_or_name> Find the full container hash with:
docker inspect <container_id_or_name> | grep IdOpen the container's hostconfig.json (path: /var/lib/docker/containers/<hash>/hostconfig.json) using vim or vi. If you prefer, cd into the container directory first: cd /var/lib/docker/containers/<hash>* In hostconfig.json, locate the "PortBindings":{} object and add the desired mappings, e.g.:
{
"PortBindings": {
"8502/tcp": [{ "HostIp": "", "HostPort": "8502" }],
"8505/tcp": [{ "HostIp": "", "HostPort": "8505" }]
}
}Also update "ExposedPorts" in config.v2.json or config.json if those files contain port entries:
{
"Config": {
"ExposedPorts": {
"8502/tcp": {},
"8505/tcp": {}
},
"Entrypoint": ["/bin/sh"]
}
}After editing, restart Docker and verify the changes:
# Restart Docker
service docker restart
# or
systemctl restart docker
# Inspect the container to confirm
docker inspect <container_id_or_name>Finally, start the container again:
docker start <container_id_or_name>Docker Desktop for Mac
On macOS, containers run inside a VM, so you need to enter that VM to edit the files. Use the tiny justincormack/nsenter1 image:
docker run -it --rm --privileged --pid=host justincormack/nsenter1--rmremoves the helper container on exit. --privileged grants access to host devices. --pid=host shares the host's PID namespace, allowing you to see host processes.
Once inside the VM, navigate to /var/lib/docker/containers and edit hostconfig.json and, if needed, config.v2.json using vi (the image lacks vim).
vi /var/lib/docker/containers/<hash>/hostconfig.json
vi /var/lib/docker/containers/<hash>/config.v2.jsonAfter modifications, restart Docker on macOS and verify the container configuration as described above.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.