14

I want to assign a container a port, so that it gets the same port after every restart of the container.

Example: I have a container, which has an Apache in it. The Apache runs on port 80 inside the container. Now, after starting the container, docker assigns a host port to the container port, for example: 49154 -> 80. But the host port changes after restart, depending on the number of running containers. I tried to specify the port in the config.json file of the container, but it gets overwritten.

Is it possible to specify the host port manually?

Thanks in advance and best regards, Chris

Chris R.
  • 415
  • 2
  • 5
  • 15

2 Answers2

16

Per the docker.io documentation: https://docs.docker.com/engine/userguide/networking/default_network/dockerlinks/

$ sudo docker run -p 80:80 <image> <cmd>

Default port redirects can be built into a container with the EXPOSE build command.

Tim
  • 1,840
  • 2
  • 15
  • 12
Mentor
  • 176
  • 1
  • 3
  • Is there a way to omit the container port (which could be found by Docker in EXPOSE) and only provide the host port ? – aurels Nov 11 '13 at 22:08
4

When you start docker, you can use the '-p' parameter.

docker run -p 80 yourimage apache2 will do what you currently have.

Now, you can specify ':' to make this port static:

docker run -p :80 -p :443 yourimage apache2

If you are using a Dockerfile with the EXPOSE instruction, it is the same thing :)

creack
  • 116,210
  • 12
  • 97
  • 73
  • 2
    Thanks for your answer. It would be easier to specify the complete mapping, so something like: docker run -p 49159:80 to specify that the host port ist 49159, which is connected to port 80 of the container. Is that possible? Thanks! – Chris R. Jun 06 '13 at 15:59
  • It is not yet possible, but feel free to open an issue on github in order to ask this feature :) – creack Jun 06 '13 at 17:07
  • 3
    That is now possible. – Stuart P. Bentley Feb 17 '14 at 19:13
  • This answer is currently wrong. Option `-p :80` also randomizes host port at each run. – kubanczyk Aug 31 '17 at 09:28