537

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?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
thasmo
  • 7,142
  • 5
  • 24
  • 30
  • 3
    Using iptables may work like this answer [Exposing a Port on a Live Docker Container](http://stackoverflow.com/questions/19897743/exposing-a-port-on-a-live-docker-container) – Choldrim May 31 '16 at 09:44
  • 3
    I 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 Kind Aug 06 '17 at 02:16
  • 3
    Old 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. – Edgar Carvalho Jul 05 '19 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 – Yaffah Jan 05 '20 at 16:15

13 Answers13

537

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,

  1. stop running container

    docker stop test01
    
  2. commit the container

    docker commit test01 test02
    

    NOTE: The above, test02 is a new image that I'm constructing from the test01 container.

  3. 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.

Evgeniy Berezovsky
  • 16,237
  • 8
  • 74
  • 131
Fujimoto Youichi
  • 5,813
  • 1
  • 13
  • 10
  • 20
    What if I want to keep the test01 name? – user69715 Oct 25 '15 at 19:13
  • 4
    @user69715 - as was described in Luca's answer - http://stackoverflow.com/a/36189165/33204 you can keep the existing of a container by creating an image of it, deleting the current container, `test01`, and then recreate it using the previously saved image. – slm May 20 '16 at 14:41
  • 14
    Anyone know if there is an open issue with Docker to allow port specification (--publish) with `docker start`? – Elijah Lynn Jun 07 '16 at 12:02
  • 9
    And what happens with the volumes in this scenario? – Andrew Savinykh May 10 '17 at 04:18
  • 5
    @AndrewSavinykh the volumes will not be transferred to the new container. However, you can link them manually: `docker inspect test01` and search for the mounts section, where you will find your volumes, that were mounted. You can then mount them in the run command: `docker run -p 8080:8080 -v 401959be5b03e750500a543e858dc021a5b98c96d10c7c595e4b100edca513d0:/data/db -td test02` – TewWe Feb 24 '18 at 22:58
  • 93
    This 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. – Arnold Zahrneinder Jun 05 '18 at 10:48
  • 37
    @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. – crockeea Oct 09 '18 at 22:05
  • 7
    @Arrrr This answer is useful when you have a heavy container that takes a long time to get in that state, then you realize that you need to open some ports.... – Johnny Willer Nov 28 '18 at 20:16
  • 3
    @Arrrr - this may indeed not be a general 'best practice'. As a tactical work round, for a persistent Linux container on Windows with clashing ports, which is what I'm using it for, it's pretty much the only way to move my work forward. – Steve Townsend Nov 29 '18 at 00:19
  • 2
    This is NOT a solution. You will lose the contents of the container. – user3335999 May 22 '19 at 16:54
  • 2
    @user3335999 how ? – Vikash Jun 11 '19 at 10:18
  • 1
    @user3335999 the files were persisted for me when I tried this -- what exactly are you referring to? – ATOMP Jun 29 '20 at 17:20
  • Can I commit new docker image not stopping existing image? – verystrongjoe Nov 09 '20 at 01:02
  • I did this with jenkins and I had to redo everything, ahaha this only ports the configuration of the container but not the content, good thing I did not delete my container yet ahaha – Oswaldo Zapata Feb 04 '21 at 19:43
362

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.

  1. Stop the container (docker stop <container_name>).
  2. Stop docker service (per Tacsiazuma's comment)
  3. Change the file.
  4. Restart your docker engine (to flush/clear config caches).
  5. 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.

kcpr
  • 785
  • 1
  • 7
  • 22
holdfenytolvaj
  • 4,187
  • 1
  • 13
  • 10
  • 4
    Perfect... There was no need to create an image with this approach – Rakib Oct 29 '16 at 21:41
  • 32
    When docker stops, it seem to overwrite your changes, so 2. stop docker, 3. change file, 4. start docker engine – Tacsiazuma Jan 25 '17 at 20:52
  • 8
    I have tried the above and it works. For more details see: https://mybrainimage.wordpress.com/2017/02/05/docker-change-port-mapping-for-an-existing-container/ – rohitmohta Feb 06 '17 at 01:59
  • 20
    It's important to stop container, stop docker engine and change both `hostconfig.json` and `config.v2.json` to make this work. Use link provided by @rohitmohta to see the details. – Kalpak Gadre Apr 26 '17 at 06:32
  • 2
    Important to remember to restart the docker engine with (service docker restart) after changing the hostconfig.json file, otherwise the file will revert back. – Andreas Presthammer Aug 27 '17 at 08:06
  • 1
    Yes `service docker stop` before making any changes to the `hostconfig.json` file. It kept getting overwritten until I stopped everything first. – dtbaker Jul 03 '18 at 12:02
  • 3
    this should be the accepted answer. Damn, so docker is caching the config and overwrites it through that cache.. – John Jul 20 '18 at 02:21
  • 7
    worked for me, just one thing if using docker app on mac, follow instructions here to get to /var/lib/docker/containers folder: https://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 – nommer Jul 27 '18 at 20:20
  • 1
    Great! The workflow should be: - Stop containers - Stop Docker - Modify hostconfig.json - Start Docker - Start container I didn't have to modify the config.v2.json file. – Monkiki Feb 08 '19 at 09:21
  • 18
    for windows, can any one please share me the location of conatiners folder.? – Vijay Mar 22 '19 at 09:29
  • 1
    if the port was not exported from the machine you have also to add it to the `config.v2.json` file, the syntax is like `"ExposedPorts":{"8080/tcp":{}}`, usually after `AttachStderr` – Frediano Ziglio Mar 17 '20 at 11:17
  • 1
    Docker Desktop no longer has these config files. – N-ate Mar 26 '20 at 02:22
  • 1
    @Vijay Why not use linux when docker is better working on it? – Mohsen Abasi Jul 22 '20 at 10:46
  • Id of the container is different than directory name. Look at https://stackoverflow.com/a/63455911/588759 – rofrol Aug 18 '20 at 10:19
  • On a separate note, this is also a great way to add mounts to an existing container. – James Mchugh Dec 19 '20 at 23:14
  • @Vijay, docker files location on Windows under WSL2: https://stackoverflow.com/questions/65546108/where-is-hostconfig-json-docker-desktop-wsl2-environment – Vadzim May 29 '21 at 08:47
54

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.

jpetazzo
  • 12,957
  • 3
  • 40
  • 44
  • 6
    This 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!_ – Partly Cloudy Nov 09 '16 at 13:47
26

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).

slm
  • 12,534
  • 12
  • 87
  • 106
Luca
  • 293
  • 3
  • 2
  • 14
    Please be aware. you will LOSE all of your data, depending on the application inside. – Barry May 23 '17 at 19:31
  • 1
    @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. – CivFan Jun 29 '20 at 18:27
  • I tried this. and it removes all my databases successfully :/ – Arslan Munir Jul 12 '20 at 14:06
  • 1
    Data 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 – Sergei Vavilov Apr 13 '21 at 18:36
26

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

  1. Create a new network if your previous container not in any named ones.

    docker network create my_network

  2. Join your existing container to the created network

    docker network connect my_network my_existing_container

  3. 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

  4. 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

  5. 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;
}
Sean C.
  • 1,198
  • 1
  • 10
  • 22
  • 1
    It'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. – Afshin Mar 09 '18 at 08: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 '18 at 10:59
  • 1
    Awesome 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. – Brooks DuBois Mar 27 '19 at 21:49
23

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.

domdambrogia
  • 1,639
  • 19
  • 26
docker-noob
  • 273
  • 2
  • 2
  • 2
    This 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. – thegeko Apr 19 '18 at 15:47
  • 4
    restart docker service in host system @thegeko – yurenchen Oct 17 '18 at 02:39
  • 1
    this works! tks! 1.stop container, 2.change files, 3.restart docker, 4.start back container – datdinhquoc Nov 20 '19 at 04:36
  • Worked perfectly for me. Appreciate you went straight to the files examples. Couldn't been able to do it without you. – RicarHincapie Jan 20 '21 at 19:50
  • Docker files location on Windows under WSL2: https://stackoverflow.com/questions/65546108/where-is-hostconfig-json-docker-desktop-wsl2-environment – Vadzim May 29 '21 at 09:32
19

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.

slm
  • 12,534
  • 12
  • 87
  • 106
rajalokan
  • 403
  • 3
  • 5
  • 2
    Ye, so it seems it's only possible to set options like port mapping at container creation. – thasmo Oct 13 '13 at 13:54
  • 26
    FYI this answer isn't entirely correct. `docker run` creates and starts a new container. It's equivalent to doing `docker create` followed by `docker start`. – Trevor Sullivan Nov 02 '16 at 18:02
16

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.

Pang
  • 8,605
  • 144
  • 77
  • 113
Mansur Ali
  • 1,468
  • 16
  • 14
  • this is a great answer ! Thank you! If I want to map `DOCKER_PORT` to `MACHINE_PORT`, which parts should be changed ? – Ciprian Tomoiagă Feb 06 '18 at 09: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! – anthony May 21 '20 at 02:28
14

we an use handy tools like ssh to accomplish this easily.

I was using ubuntu host and ubuntu based docker image.

  1. Inside docker have openssh-client installed.
  2. 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.

melchi
  • 489
  • 5
  • 8
9

To change HostPort of a container on Windows 10

# list all containers
$ docker ps -a
$ docker stop docker101tutorial 
# Use grep or rg 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
$ grep -rl --include=config.v2.json fff0a4b22d /var/lib/docker/containers/
/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. Press Enter.
  • Do not start/stop docker101tutorial now. Otherwise changes to HostPort 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.

rofrol
  • 12,038
  • 7
  • 62
  • 63
  • 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"}] – NiharGht Apr 11 '21 at 06:54
4
  1. Stop the docker engine and that container.
  2. Go to /var/lib/docker/containers/${container_id} directory and edit hostconfig.json
  3. Edit PortBindings.HostPort that you want the change.
  4. Start docker engine and container.
Kos
  • 3,847
  • 8
  • 29
  • 34
ezileli
  • 143
  • 1
  • 5
0

I am developing a dockerizer go package for deploying batch processing apps in docker containers. My package includes a MessageBroker component that has 3 ports to publish: jobAgentPort, backendPort, frontendPort.

I'll cut a long story short by suggesting that it's better to design an endpointProvider component that is embedded into your server/proxy/broker.

That is, the container deployment is at least a 2 step process.

  1. the endpointProvider component is created and cached in the related package by jobId or similar key.
  2. the server/proxy/broker is built into a binary where your code accepts an endpointConfig component that is output by the endpointProvider.

eg the server/proxy/broker constructor has a signature: NewMessageBroker(epc *EndpointConfig) *MessageBroker. Then, using the docker-client api, a container image is created and finally the container is started (docker run) and ports are published using the endpointConfig that exposes the port values.

pmg7670
  • 41
  • 3
  • Please learn how to properly format the post. Please check how to use markdown in SO for proper formatting. – Muhammad Tariq Apr 14 '21 at 12:58
  • If you mean that the answer must have a code solution, then I don't agree. In this case the right answer is the right design pattern – pmg7670 Apr 19 '21 at 03:21
  • Did I say "use code" or "code solution" anywhere? If you read carefully, I am suggesting you to `Properly Format` your post using markdown. Here is the link to help you understand how to use markdown in SO https://stackoverflow.com/editing-help – Muhammad Tariq Apr 19 '21 at 05:05
  • @MuhammadTariq thanks for your info – pmg7670 Apr 22 '21 at 09:41
-1

For Windows & Mac Users, there is another pretty easy and friendly way to change the mapping port:

  1. download kitematic

  2. go to the settings page of the container, on the ports tab, you can directly modify the published port there.

  3. start the container again

FrankK
  • 422
  • 7
  • 19
john
  • 37
  • 1
  • 4
    I 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. – VeganHunter Jul 03 '18 at 05:41
  • 1
    I 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 – 2b77bee6-5445-4c77-b1eb-4df3e5 Jun 07 '19 at 21:00