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

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github