How can I expose more than 1 port with Docker?

DockerDocker Networking

Docker Problem Overview


So I have 3 ports that should be exposed to the machine's interface. Is it possible to do this with a Docker container?

Docker Solutions


Solution 1 - Docker

To expose just one port, this is what you need to do:

docker run -p <host_port>:<container_port>

To expose multiple ports, simply provide multiple -p arguments:

docker run -p <host_port1>:<container_port1> -p <host_port2>:<container_port2>

Solution 2 - Docker

###Step1 In your Dockerfile, you can use the verb EXPOSE to expose multiple ports.
e.g.

EXPOSE 3000 80 443 22

###Step2 You then would like to build an new image based on above Dockerfile.
e.g.

docker build -t foo:tag .

###Step3 Then you can use the -p to map host port with the container port, as defined in above EXPOSE of Dockerfile.
e.g.

docker run -p 3001:3000 -p 23:22

In case you would like to expose a range of continuous ports, you can run docker like this:

docker run -it -p 7100-7120:7100-7120/tcp 

Solution 3 - Docker

if you use docker-compose.ymlfile:

services:
    varnish:
        ports:
            - 80
            - 6081

You can also specify the host/network port as HOST/NETWORK_PORT:CONTAINER_PORT

varnish:
    ports:
        - 81:80
        - 6081:6081

Solution 4 - Docker

If you are creating a container from an image and like to expose multiple ports (not publish) you can use the following command:

docker create --name `container name` --expose 7000 --expose 7001 `image name`

Now, when you start this container using the docker start command, the configured ports above will be exposed.

Solution 5 - Docker

Use this as an example:

docker create --name new_ubuntu -it -p 8080:8080 -p  15672:15672 -p 5432:5432   ubuntu:latest bash

look what you've created(and copy its CONTAINER ID xxxxx):

docker ps -a 

now write the miracle maker word(start):

docker start xxxxx

good luck

Solution 6 - Docker

Only one point to add. you have the option to specify a range of ports to expose in the dockerfile and when running it:

on dockerfile:

EXPOSE 8888-8898

Build image:

docker build -t <image_name>:<version> -f dockerfile .

When running the image:

docker run -it -p 8888-8898:8888-8898 -v C:\x\x\x:/app <image_name>:<version>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnubelaView Question on Stackoverflow
Solution 1 - DockerTania AngView Answer on Stackoverflow
Solution 2 - DockermainframerView Answer on Stackoverflow
Solution 3 - DockerRashidul IslamView Answer on Stackoverflow
Solution 4 - DockerPhantomReferenceView Answer on Stackoverflow
Solution 5 - DockerAramis NSRView Answer on Stackoverflow
Solution 6 - DockerHMSView Answer on Stackoverflow