Guide to Modifying Docker Container Port Mappings
Guide to Modifying Docker Container Port Mappings
If you need to modify the port mappings for an existing Docker container, such as one with the ID 123456
, follow these steps carefully. This guide assumes that you have administrative access to the Docker host and are familiar with using a text editor like vim
on Linux systems.
service docker stop
Step 1: Modify hostconfig.json
First, edit the hostconfig.json
file located in the container’s directory:
sudo vim /var/lib/docker/containers/123456/hostconfig.json
Look for the "PortBindings"
configuration. If your container was started with port mappings, this object will not be empty. Add or update the port bindings as follows:
{
"PortBindings": {
"5700/tcp": [{
"HostIp": "",
"HostPort": "10086"
}],
"6700/tcp": [{
"HostIp": "",
"HostPort": "6700"
}],
"9000/tcp": [{
"HostIp": "",
"HostPort": "8080"
}]
}
}
- The keys with
/tcp
suffix represent the internal ports of the Docker container. - The
HostPort
values inside the array objects specify the external ports on the host machine that will forward to the respective internal ports.
Note: Leave the
HostIp
field empty if you want to bind to all interfaces (0.0.0.0
). Fill it with a specific IP address if you want to restrict access to a particular network interface.
Step 2: Modify config.v2.json
Next, edit the config.v2.json
file also located in the container’s directory:
sudo vim /var/lib/docker/containers/123456/config.v2.json
Find the "Config"
section within this larger configuration object. If no port mappings were previously configured, there might not be an "ExposedPorts"
field. Add the exposed ports as shown below:
{
"Config": {
"ExposedPorts": {
"5700/tcp": {},
"6700/tcp": {},
"9000/tcp": {}
}
}
}
The "ExposedPorts"
field indicates which ports inside the container should be exposed. This works in conjunction with the "PortBindings"
settings from the previous step.
service docker start
Important Considerations
-
Restart the Container: After modifying these files, you must restart the container for changes to take effect. However, directly editing these files is not recommended as a standard practice because Docker does not officially support this method. It can lead to inconsistencies and potential issues.
-
Preferred Method: To avoid possible problems, use Docker CLI commands or Docker Compose to manage port mappings when starting containers. For example:
docker run -p 10086:5700 -p 6700:6700 -p 8080:9000 ...
-
Backup Configuration Files: Before making any changes, ensure you have backups of the original configuration files in case you need to revert them.
This approach should help you set up the desired port forwarding for your Docker container. Remember to always follow best practices and official guidelines provided by Docker documentation.
Comments
Post a Comment