I'm not sure if I've misunderstood something here, but it seems like it's only possible to set port mappings by creating a new container from an image. Is there a way to assign a port mapping to an existing Docker container?
-
4Using iptables may work like this answer Exposing a Port on a Live Docker Container– CholdrimMay 31, 2016 at 9:44
-
6I suspect this is by design. Docker is trying to force you to be "repeatable" and the container is a type of "system of record." Anything you do as step that doesn't affect the container would be an easily lost manual step. Said another way: You want your container to represent all the configuration that's necessary to operate. So if you want to open a new port, then you need to create a new container.– Lance KindAug 6, 2017 at 2:16
-
4Old question and I'm not answering it, but I would like to say that maybe you and people upovting this question and answers may have completely misunderstood the concept of docker. Docker are for stateless application, that can scale up or down many times. You should never persist something inside the container for a production enviroment that can't be recreated, if you need to persist, map the directories. Docker is not something like a "light vm", maybe what you are looking for is linuxcontainers.org, lxd is based on docker concept but with a "light vm" in mind.– EdgarJul 5, 2019 at 14:09
-
just in case this might help, it is possible to use the "Kitematic" tool to add port mapping to already running containers. This should imply that there must be docker command to do exactly the same thing but with a little googling :) Good luck– YaffahJan 5, 2020 at 16:15
15 Answers
I'm also interested in this problem.
As @Thasmo mentioned, port forwardings can be specified ONLY with docker run
(and docker create
) command.
Other commands, docker start
does not have -p
option and docker port
only displays current forwardings.
To add port forwardings, I always follow these steps,
stop running container
docker stop test01
commit the container
docker commit test01 test02
NOTE: The above,
test02
is a new image that I'm constructing from thetest01
container.re-run from the commited image
docker run -p 8080:8080 -td test02
Where the first 8080 is the local port and the second 8080 is the container port.
-
27
-
21Anyone know if there is an open issue with Docker to allow port specification (--publish) with
docker start
? Jun 7, 2016 at 12:02 -
12
-
128This is a terrible solution, I have no idea how it managed to earn 250 upvotes. Maybe those how upvoted didn't know what kind of mess this solution causes. Yes, it's terrible, and it is equal to starting a new container running on a different port. Jun 5, 2018 at 10:48
-
54@Arrrr Perhaps you'd like to leave a better answer? I'm sure we'd all appreciate if you told us the much better way to do this.– crockeeaOct 9, 2018 at 22:05
You can change the port mapping by directly editing the hostconfig.json
file at
/var/lib/docker/containers/[hash_of_the_container]/hostconfig.json
or /var/snap/docker/common/var-lib-docker/containers/[hash_of_the_container]/hostconfig.json
, I believe, if You installed Docker as a snap.
You can determine the [hash_of_the_container] via the docker inspect <container_name>
command and the value of the "Id" field is the hash.
- Stop the container (
docker stop <container_name>
). - Stop docker service (per Tacsiazuma's comment)
- Change the file.
- Restart your docker engine (to flush/clear config caches).
- Start the container (
docker start <container_name>
).
So you don't need to create an image with this approach. You can also change the restart flag here.
P.S. You may visit https://docs.docker.com/engine/admin/ to learn how to correctly restart your docker engine as per your host machine. I used sudo systemctl restart docker
to restart my docker engine that is running on Ubuntu 16.04.
-
42When docker stops, it seem to overwrite your changes, so 2. stop docker, 3. change file, 4. start docker engine Jan 25, 2017 at 20:52
-
10I have tried the above and it works. For more details see: mybrainimage.wordpress.com/2017/02/05/… Feb 6, 2017 at 1:59
-
27It's important to stop container, stop docker engine and change both
hostconfig.json
andconfig.v2.json
to make this work. Use link provided by @rohitmohta to see the details. Apr 26, 2017 at 6:32 -
7worked for me, just one thing if using docker app on mac, follow instructions here to get to /var/lib/docker/containers folder: stackoverflow.com/a/41226917/2048266, basically run
screen ~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/tty
Once you get the tty running you can navigate to /var/lib/docker– nommerJul 27, 2018 at 20:20 -
23for windows, can any one please share me the location of conatiners folder.?– VijayMar 22, 2019 at 9:29
If by "existing" you mean "running", then it's not (currently) possible to add a port mapping.
You can, however, dynamically add a new network interface with e.g. Pipework, if you need to expose a service in a running container without stopping/restarting it.
-
15This should be the top answer. Succinct and it addresses OP's question which none of the others do! Sometimes a negative result is a result! Nov 9, 2016 at 13:47
Editing hostconfig.json seems to not working now. It only ends with that port being exposed but not published to host. Commiting and recreating containers is not the best approach to me. No one mentioned docker network
?
The best solution would be using reversed proxy within the same network
Create a new network if your previous container not in any named ones.
docker network create my_network
Join your existing container to the created network
docker network connect my_network my_existing_container
Start a reversed proxy service(e.g. nginx) publishing the ports you need, joining the same network
docker run -d --name nginx --network my_network -p 9000:9000 nginx
Optionally remove the default.conf in nginx
docker exec nginx rm /etc/nginx/conf.d/default.conf
Create a new nginx config
server { listen 9000; location / { proxy_pass http://my_existing_container:9000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } }
Copy the config to nginx container.
docker cp ./my_conf.conf nginx:/etc/nginx/conf.d/my_conf.conf
Restart nginx
docker restart nginx
Advantages: To publish new ports, you can safely stop/update/recreate nginx container as you wish without touching the business container. If you need zero down time for nginx, it is possible to add more reversed proxy services joining the same network. Besides, a container can join more than one network.
Edit:
To reverse proxy non-http services, the config file is a bit different. Here is a simple example:
upstream my_service {
server my_existing_container:9000;
}
server {
listen 9000;
proxy_pass my_service;
}
-
1It's amazing and practical, but for enterprise systems this approach seems to be obfuscating. It's much more better to let a single system controls the workflow.– AfshinMar 9, 2018 at 8:30
-
1@Afshin Well for enterprise systems or projects, I think this solution is better than recreating(causes down time) or hacking hostconfig.json file(at least not officially introduced). The extra container just exposes your business container's internal port, rather than makeing any changes to it.– Sean C.Mar 10, 2018 at 10:59
-
1Awesome approach. I needed to configure nginx differently for my container to work behind a proxy, but seems like the correct way to do things. Works for blue-green deployment too. Mar 27, 2019 at 21:49
-
2Nice approach! I think using TCP proxy like
socat
could be even easier. Jan 28, 2022 at 13:44 -
1I like
reproxy
because it's easier to configure:docker create -p EXTERNAL_PORT:8080 --name reproxy_container --network NETWORK_NAME umputun/reproxy --static.enabled --static.rule=*,^/(.*),http://ORIGINAL_CONTAINER:INTERNAL_PORT/$1
– WinandFeb 25, 2022 at 18:18
In Fujimoto Youichi's example test01
is a container, whereas test02
is an image.
Before doing docker run
you can remove the original container and then assign the container the same name again:
$ docker stop container01
$ docker commit container01 image01
$ docker rm container01
$ docker run -d -P --name container01 image01
(Using -P
to expose ports to random ports rather than manually assigning).
-
29Please be aware. you will LOSE all of your data, depending on the application inside.– BarryMay 23, 2017 at 19:31
-
2@Barry - in what case? This commits the container to an image, which saves all your data in the container to an image. Any volumes or mounts the original container used will of course still be there, since they're separate from containers and images. So I don't follow.– CivFanJun 29, 2020 at 18:27
-
2
-
2Data can be stored on a volume.. Try inspecting the container for volumes
docker inspect container01
before removing, keep the volume name and mount it when running a new container Apr 13, 2021 at 18:36 -
@CivFan "Any volumes or mounts the original container used will of course still be there, since they're separate from containers and images." - You're very close to following: yes, data in a volume or mount will be fine. But if data is not in a volume or mount, it will be lost - and data is not always in volumes or mounts, thus data will sometimes be lost. Feb 6, 2022 at 0:56
If you are not comfortable with Docker depth configuration, iptables would be your friend.
iptables -t nat -A DOCKER -p tcp --dport ${YOURPORT} -j DNAT --to-destination ${CONTAINERIP}:${YOURPORT}
iptables -t nat -A POSTROUTING -j MASQUERADE -p tcp --source ${CONTAINERIP} --destination ${CONTAINERIP} --dport ${YOURPORT}
iptables -A DOCKER -j ACCEPT -p tcp --destination ${CONTAINERIP} --dport ${YOURPORT}
This is just a trick, not a recommended way. This works with my scenario because I could not stop the container.
Note: you can use the -D
flag to remove/revert/delete a rule from iptables; which will be necessary if you ever remove the container and wish to use the port.
-
this is a great answer ! Thank you! If I want to map
DOCKER_PORT
toMACHINE_PORT
, which parts should be changed ? Feb 6, 2018 at 9:10 -
Note docker wil not know about this manual addition. SO entries are not removed when you later restart the service with the docker exposing the ports properly. So when anything changes, be sure to check iptables very carefully. Especially look for duplicate entries!– anthonyMay 21, 2020 at 2:28
-
Great answer. Don't forget to make changes in the host file of the computer accessing the docker from the local network for the needed application.– AkifJan 21, 2022 at 15:56
-
-
If you run docker run <NAME>
it will spawn a new image, which most likely isn't what you want.
If you want to change a current image do the following:
docker ps -a
Take the id of your target container and go to:
cd /var/lib/docker/containers/<conainerID><and then some:)>
Stop the container:
docker stop <NAME>
Change the files
vi config.v2.json
"Config": {
....
"ExposedPorts": {
"80/tcp": {},
"8888/tcp": {}
},
....
},
"NetworkSettings": {
....
"Ports": {
"80/tcp": [
{
"HostIp": "",
"HostPort": "80"
}
],
And change file
vi hostconfig.json
"PortBindings": {
"80/tcp": [
{
"HostIp": "",
"HostPort": "80"
}
],
"8888/tcp": [
{
"HostIp": "",
"HostPort": "8888"
}
]
}
Restart your docker and it should work.
-
2This did not work for me on Docker version 17.09.0-ce. After I started the container config files got overwritten back to old values.– thegekoApr 19, 2018 at 15:47
-
6
-
5this works! tks! 1.stop container, 2.change files, 3.restart docker, 4.start back container– DeeNov 20, 2019 at 4:36
-
Worked perfectly for me. Appreciate you went straight to the files examples. Couldn't been able to do it without you. Jan 20, 2021 at 19:50
-
1Docker files location on Windows under WSL2: stackoverflow.com/questions/65546108/…– VadzimMay 29, 2021 at 9:32
Not sure if you can apply port mapping a running container. You can apply port forwarding while running a container which is different than creating a new container.
$ docker run -p <public_port>:<private_port> -d <image>
will start running container. This tutorial explains port redirection.
-
3Ye, so it seems it's only possible to set options like port mapping at container creation.– thasmoOct 13, 2013 at 13:54
-
36FYI this answer isn't entirely correct.
docker run
creates and starts a new container. It's equivalent to doingdocker create
followed bydocker start
.– user189198Nov 2, 2016 at 18:02
To change HostPort of a container on Docker Desktop (on Windows 10 / MacOS)
# list all containers
$ docker ps -a
$ docker stop docker101tutorial
# Use grep to get id of container
$ docker inspect docker101tutorial | grep -i id
"Id": "sha256:fff0a4b22d6f3d2eb8d2748b8a8bbc9967ea87199988acee8e86ac70bce9c3eb",
# run plain ubuntu docker image with shell and change it's namespace to docker host
# https://stackoverflow.com/questions/60408574/how-to-access-var-lib-docker-in-windows-10-docker-desktop/60411313#60411313
# https://forums.docker.com/t/the-location-of-images-in-docker-for-windows/19647/4
$ docker run -it --privileged --pid=host ubuntu nsenter -t 1 -m -u -i sh
# We want to find out the directory of docker101tutorial container. We are looking for:
# `"Image":"sha256:fff0a4b22d6f3d2eb8d2748b8a8bbc9967ea87199988acee8e86ac70bce9c3eb"`
# in /var/lib/docker/containers/*/config.v2.json
$ find /var/lib/docker/containers/ -name config.v2.json -exec grep -H fff0a4b22d {} \;
/var/lib/docker/containers/c1eda20b30f058bce9f8ece3b47a21641df5b399770e12ab57416a954d3c8bbf/config.v2.json
# edit it
$ vi /var/lib/docker/containers/c1eda20b30f058bce9f8ece3b47a21641df5b399770e12ab57416a954d3c8bbf/hostconfig.json
- Press
i
for insert mode. - Change
"HostPort":"80"
to"HostPort":"8092"
- Press
Escape
and write:wq
. PressEnter
. - Do not start/stop
docker101tutorial
now. Otherwise changes toHostPort
will be reverted. - Right click Docker Desktop tray icon and click Restart.
- In Docker Desktop's list of containers, look at your container. Displayed port should change to
8092
. - Start your container. Now it will be mapped to port
8092
on host.
Based on @holdfenytolvaj answer.
-
This worked, I was trying to create a postgres service on WIndows 10, I had created the container with -p port publish, but for some strange reason it did not publish the port 5432. This worked. Any idea why this is happening? FYI - in the host file I added this to work "PortBindings":{"5432/tcp":[{"HostIp":"","HostPort":"5432"}]– NiharGhtApr 11, 2021 at 6:54
-
1For some reason, grep on the latest Ubuntu does not recognize
--include
option but it's possible to use the find command to do the same:find /var/lib/docker/containers/ -name config.v2.json -exec grep -H f7828c0aa {} \;
– kreiganJul 2, 2021 at 21:18 -
How to start this debian container later? Can't start back in command line– bodichDec 18, 2022 at 18:42
-
1My two cents on this: on Windows 10 Home Edition I just tried to do this many times, and the port was simply never forwarded by Docker Desktop. I ended up installing an SSH server on Windows (the Cygwin SSH server in this case) and opening a reverse forwarding tunnel as mentioned on melchi's answer. Protip: on Windows you can open cmd.exe and use your workstation's WSL IP address (you can find it on Task Manager under the Ethernet labeled as "vEthernet (WSL)") as destination of your SSH from the container.– RAKKAug 31 at 19:25
we an use handy tools like ssh to accomplish this easily.
I was using ubuntu host and ubuntu based docker image.
- Inside docker have openssh-client installed.
- Outside docker (host) have openssh-server server installed.
when a new port is needed to be mapped out,
inside the docker run the following command
ssh -R8888:localhost:8888 <username>@172.17.0.1
172.17.0.1 was the ip of the docker interface
(you can get this by running
ifconfig docker0 | grep "inet addr" | cut -f2 -d":" | cut -f1 -d" "
on the host).
here I had local 8888 port mapped back to the hosts 8888. you can change the port as needed.
if you need one more port, you can kill the ssh and add one more line of -R to it with the new port.
I have tested this with netcat.
-
Thank you for this suggestion, I ended up resorting to it after failing to connect to a Gitlab container on Docker Desktop for Windows 10 no matter what I did.– RAKKAug 31 at 19:26
- Stop the docker engine and that container.
- Go to
/var/lib/docker/containers/${container_id}
directory and edithostconfig.json
- Edit
PortBindings.HostPort
that you want the change. - Start docker engine and container.
PORTAINER METHOD
If anyone is using portainer, I found this solution to be "Gui friendly and safe"
-
This method is used in the following YouTube video explaining vpn binding with docker (uses portainer) youtube.com/watch?v=vUyHGF1HMsw– MrMeseesJun 11 at 3:35
I had this situation with my container:
127.0.0.1:8050->8000
And I solved it with one iptalbes rule:
iptables -t nat -I DOCKER 1 -p tcp --dport ${HOST_PORT} -j DNAT --to-destination ${CONTAINER_IP}:${CONTAINER_PORT}
In this example HOST_PORT
is 8050 and CONTAINER_PORT
is 8000. To find CONTAINER_IP
use docker inspect
command.
To remove the iptables rule use this command:
iptables -t nat -D DOCKER 1
For Windows & Mac Users, there is another pretty easy and friendly way to change the mapping port:
download kitematic
go to the settings page of the container, on the ports tab, you can directly modify the published port there.
start the container again
-
5I tried this approach. Kinematic applied the port mappings, indeed. Howeverto apply them, it re-created my container from the original image. So if you are afraid of loosing the changes made in the container itself, do not use this method. Jul 3, 2018 at 5:41
-
1I preferred this, I get that it doesn't answer the question, and it creates a new container. But at least it works, and this SO result showed up during my search. +1 Jun 7, 2019 at 21:00
How do I assign a port mapping to an existing Docker container ?
It's very Simple. There is two thing one is local server PORT like 800,8080 etc. on your machine and the second one is your container PORT which you want to map. Docker Port mapping
docker run -p 8080:8080 <Image ID>
To get Image Id you can use
docker ps
-
2This does not answer the question since OP was asking whether an existing container could be re-assigned a new port. Using
run
creates a new container. Jul 7, 2022 at 22:57