跳到主要內容
275
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?
  • 3
    Using iptables may work like this answer Exposing a Port on a Live Docker Container – Choldrim May 31 '16 at 9:44
  • 1
    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 6 '17 at 2:16

12 Answers

330
I'm also interested in this problem.
As @Thasmo mentioned, port forwardings can be specified ONLY with docker run 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.
  • 5
    What if I want to keep the test01 name? – user69715 Oct 25 '15 at 19:13
  • 9
    Anyone know if there is an open issue with Docker to allow port specification (--publish) with docker start? – Elijah Lynn Jun 7 '16 at 12:02
  • 6
    And what happens with the volumes in this scenario? – Andrew Savinykh May 10 '17 at 4:18
  • 22
    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. – Arrrr Jun 5 '18 at 10:48
  • 3
    @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 9 '18 at 22:05
161
You can change the port mapping by directly editing the hostconfig.json file at /var/lib/docker/containers/[hash_of_the_container]/hostconfig.json
You can determine the [hash_of_the_container] via the docker inspect command and the value of the "Id" field is the hash.
1) stop the container 
2) change the file
3) restart your docker engine (to flush/clear config caches)
4) start the container
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
21
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.
  • 1
    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 9 '16 at 13:47
16
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 : -d   
will start running container. This tutorial explains port redirection.
  • 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
  • 7
    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 2 '16 at 18:02
11
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).
  • 2
    Please be aware. you will LOSE all of your data, depending on the application inside. – Barry May 23 '17 at 19:31 
3
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;
}
  • 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 9 '18 at 8:30
  • @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 
3
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 @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.
1
The other way around you 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 container i hope will help you as well.
1
If you run docker run  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/
Stop the container:
docker stop 
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.
0
As a complement of the response of @Fujimoto-Youichi
You can also use $ docker run -P CONTAINER to map ports randomly while creating your container, but be careful with security ascpect !
-P eq to --publish-all : "It publish all exposed ports to random ports" ,
then run docker inspect CONTAINER to fin ports mapping as shown in the image below :
docker inspect for a rabbitmq container show all ports mapping
Read more about docker run -P in docker run
-3
For Windows & Mac Users, now there is another pretty easy and friendly way to change the mapping port:
  1. download the kitematic
  2. go the settings page of the container, on ports tab, you can directly modify the published port there.
  3. start the container again
  • 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 3 '18 at 5:41
-8
If you simply want to change the port of the running container, you do:
  1. stop existing container
    sudo docker stop NAME
  2. now restart with the new port mapping
    sudo docker run -d -p 81:80 NAME
where as:
"-d" to background / deamon the docker
"-p" enable port mapping
"81" external (exposed) port you use to access with your browser
"80" internal docker container listen port

留言

這個網誌中的熱門文章

2017通訊大賽「聯發科技物聯網開發競賽」決賽團隊29強出爐!作品都在11月24日頒獎典禮進行展示

2017通訊大賽「聯發科技物聯網開發競賽」決賽團隊29強出爐!作品都在11月24日頒獎典禮進行展示 LIS   發表於 2017年11月16日 10:31   收藏此文 2017通訊大賽「聯發科技物聯網開發競賽」決賽於11月4日在台北文創大樓舉行,共有29個隊伍進入決賽,角逐最後的大獎,並於11月24日進行頒獎,現場會有全部進入決賽團隊的展示攤位,總計約為100個,各種創意作品琳琅滿目,非常值得一看,這次錯過就要等一年。 「聯發科技物聯網開發競賽」決賽持續一整天,每個團隊都有15分鐘面對評審團做簡報與展示,並接受評審們的詢問。在所有團隊完成簡報與展示後,主辦單位便統計所有評審的分數,並由評審們進行審慎的討論,決定冠亞季軍及其他各獎項得主,結果將於11月24日的「2017通訊大賽頒獎典禮暨成果展」現場公佈並頒獎。 在「2017通訊大賽頒獎典禮暨成果展」現場,所有入圍決賽的團隊會設置攤位,總計約為100個,展示他們辛苦研發並實作的作品,無論是想觀摩別人的成品、了解物聯網應用有那些新的創意、尋找投資標的、尋找人才、尋求合作機會或是單純有興趣,都很適合花點時間到現場看看。 頒獎典禮暨成果展資訊如下: 日期:2017年11月24日(星期五) 地點:中油大樓國光廳(台北市信義區松仁路3號) 我要報名參加「2017通訊大賽頒獎典禮暨成果展」>>> 在參加「2017通訊大賽頒獎典禮暨成果展」之前,可以先在本文觀看各團隊的作品介紹。 決賽29強團隊如下: 長者安全救星 可隨意描繪或書寫之電子筆記系統 微觀天下 體適能訓練管理裝置 肌少症之行走速率檢測系統 Sugar Robot 賽亞人的飛機維修輔助器 iTemp你的溫度個人化管家 語音行動冰箱 MR模擬飛行 智慧防盜自行車 跨平台X-Y視覺馬達控制 Ironmet 菸消雲散 無人小艇 (Mini-USV) 救OK-緊急救援小幫手 穿戴式長照輔助系統 應用於教育之模組機器人教具 這味兒很台味 Aquarium Hub 發展遲緩兒童之擴增實境學習系統 蚊房四寶 車輛相控陣列聲納環境偵測系統 戶外團隊運動管理裝置 懷舊治療數位桌曆 SeeM智能眼罩 觸...
opencv4nodejs Asynchronous OpenCV 3.x Binding for node.js   122     2715     414   0   0 Author Contributors Repository https://github.com/justadudewhohacks/opencv4nodejs Wiki Page https://github.com/justadudewhohacks/opencv4nodejs/wiki Last Commit Mar. 8, 2019 Created Aug. 20, 2017 opencv4nodejs           By its nature, JavaScript lacks the performance to implement Computer Vision tasks efficiently. Therefore this package brings the performance of the native OpenCV library to your Node.js application. This project targets OpenCV 3 and provides an asynchronous as well as an synchronous API. The ultimate goal of this project is to provide a comprehensive collection of Node.js bindings to the API of OpenCV and the OpenCV-contrib modules. An overview of available bindings can be found in the  API Documentation . Furthermore, contribution is highly appreciated....

完形心理學!?讓我們了解“介面設計師”為什麼這樣設計

完形心理學!?讓我們了解“介面設計師”為什麼這樣設計 — 說服客戶與老闆、跟工程師溝通、強化設計概念的有感心理學 — 情況 1 : 為何要留那麼多空白? 害我還要滾動滑鼠(掀桌) 情況 2 : 為什麼不能直接用一頁展現? 把客戶的需求塞滿不就完工啦! (無言) 情況 3: 這種設計好像不錯,但是為什麼要這樣做? (直覺大神告訴我這樣設計,但我說不出來為什麼..) 雖然世界上有許多 GUI 已經走得又長又遠又厲害,但別以為這種古代人對話不會出現,一直以來我們只是習慣這些 GUI 被如此呈現,但為何要這樣設計我們卻不一定知道。 由於 完形心理學 歸納出人類大腦認知之普遍性的規則,因此無論是不是 UI/UX 設計師都很適合閱讀本篇文章。但還是想特別強調,若任職於傳統科技公司,需要對上說服老闆,需要平行說服(資深)工程師,那請把它收進最愛;而習慣套用設計好的 UI 套件,但不知道為何這樣設計的 IT 工程師,也可以透過本文來強化自己的產品說服力。 那就開始吧~(擊掌) 完形心理學,又稱作格式塔(Gestalt)心理學,於二十世紀初由德國心理學家提出 — 用以說明人類大腦如何解釋肉眼所觀察到的事物,並轉化為我們所認知的物件。它可說是現代認知心理學的基礎,其貫徹的概念就是「整體大於個體的總合 “The whole is other than the sum of the parts.” —  Kurt Koffka」。 若深究完整的理論將會使本文變得非常的艱澀,因此筆者直接抽取個人認為與 UI 設計較為相關的 7 個原則(如下),並搭配實際案例做說明。有興趣了解全部理論的話可以另外 Google。 1. 相似性 (Similarity)  — 我們的大腦會把相似的事物看成一體 如果數個元素具有類似的尺寸、體積、顏色,使用者會自動為它們建立起關聯。這是因為我們的眼睛和大腦較容易將相似的事物組織在一起。如下圖所示,當一連串方塊和一連串的圓形並排時,我們會看成(a)一列方塊和兩列圓形(b)一排圓形和兩排三角形。 對應用到介面設計上,FB 每則文章下方的按鈕圖標(按讚 Like / 留言Comment / 分享 Share)雖然功能各不相同,但由於它們在視覺上顏色、大小、排列上的相似性,用戶會將它們視認為...