What Is the Difference between Docker-Compose Ports and Expose?

Better Stack Team
Updated on August 1, 2022

You may have wondered what is the difference between docker-compose ports and docker-compose expose. Here is a clear explanation to help you better understand the matter.

Ports

Ports mentioned in the docker-compose.yml file will be shared among different services started by the docker-compose.yml. These ports will be then exposed to the host to a random port or predefined port.

This configuration will set the port to 3306 for the services and then expose this port to the host as port 32769 (this port will be chosen randomly)

 
mysql:
  image: mysql:5.7
  ports:
    - "3306"
 
docker-compose ps
Output:
Name                     Command               State            Ports
-------------------------------------------------------------------------------------
  mysql_1       docker-entrypoint.sh mysqld      Up      0.0.0.0:32769->3306/tcp

Expose

On the other hand, expose ports mentioned in the docker-compose.yml file will be only accessible to linked services and won’t be exposed to the host.

The following example will set the expose the port 3306 only to the connected services and won't expose the port to the host:

 
mysql:
  image: mysql:5.7
  expose:
    - "3306"
 
docker-compose ps
Output:
Name                  Command             State    Ports
---------------------------------------------------------------
 mysql_1      docker-entrypoint.sh mysqld   Up      3306/tcp
Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack