Low Orbit Flux Logo 2 F

Docker How To Expose Or Publish Port

We are going to show you how to expose and publish ports on Docker containers. It turns out that this isn’t too hard and once you get a handle on what the commands are doing it makes a lot of sense.

Quick answer: - This is the command that you are probably looking for:


docker run -tid -p 1234:80 nginx   

Exposing Ports

Exposing a port makes it available inside the container and on the Docker network between containers. It will be available for inter container communication. If one container exposes a port, another container will be able to access that port.

Exposing ports does NOT make them available on the host system. To do that you will need to publish the ports.

You can expose a port inside a docker file like this:


EXPOSE 8080    

That will use TCP by default. You could explicitly specify UDP or TCP like this:


EXPOSE 8080/tcp    
EXPOSE 8080/udp

Here is an example:


FROM ubuntu
RUN apt update
RUN apt install nginx -y
EXPOSE 80  
CMD ["/usr/sbin/nginx"]

You can also expose from command line like this:


docker run -d --expose=8080 nginx 

Or using a range like this:

   
docker run -d --expose=1000-2000 nginx    

Publishing Ports

Publishing ports will make them available on the host system binding them to the actual NIC.

Here is an example showing how you would publish container port 80 to port 1234 on the local host system.


docker run -tid -p 1234:80 nginx   

Here are some more example commands showing different ways in which you may choose to publish ports:

docker run -tid -p 80:5000 ubuntu bind port
docker run -tid -p 8000-9000:5000 ubuntu bind port to range
docker run -tid -p 80:5000/udp ubuntu udp ports
docker run -tid -p 127.0.0.1:80:5000 ubuntu bind port on an interface
docker run -tid -p 127.0.0.1::5000 ubuntu bind any port, specific interface
docker run -tid -P ubuntu exposed ports to random ports

You can’t actually publish a port inside a Dockerfile. This is by design. It is not meant to be built into the image but configured at run time.

You could publish a port using a Docker compose file like this:


nginxserver1:
  image: myname/nginxserver1
  ports:
    - 80:8080

Difference Between Exposing vs Publishing Ports

Exposing a port only makes that port available inside the container and on the local network between Docker containers. The port will be available for inter container communication. Publishing a port makes it available outside the container on the actual host system. Exposing a port won’t result in the port being published but publishing will result in the port being exposed.