Julien Le Coupanec
Julien Le Coupanec

Reputation: 7988

Do I have to expose the port if I am using the ports config?

Do I have to expose the port if I am using the ports config?

In the docker-compose.yml below, do I have to keep expose 2022 or can I remove it? Is there a difference between them?

  myproject-app:
    build: ../myproject-app
    container_name: myproject-app
    image: myproject-app
    expose:
      - 2022
    ports:
      - 2022:2022
    volumes:
      - ../myproject-app/:/home/myproject/myproject-app/
      - /home/myproject/myproject-app/node_modules

Upvotes: 0

Views: 83

Answers (2)

David Maze
David Maze

Reputation: 158647

"Expose" means basically nothing in modern Docker. There is pretty much no reason to put an expose: line in your docker-compose.yml file. It's considered polite to include an EXPOSE line in your Dockerfile to document what port(s) your service will listen on, but it's not strictly necessary.

In modern Docker, with named networks, any container can connect to any port of any other container on the same network, provided a process is listening there. Before there were named networks, one container had to explicitly "link" to another to be able to call it, and then it could only reach the exposed ports of the target container. This setup is considered obsolete now (you never need links: either).

Plain Docker has an option (docker run -P, with a capital P) to publish all exposed ports on random host ports. Compose doesn't have an equivalent option. Ports that are exposed but not published also show up in the docker ps output. But those are really the only things "expose" does at all.

Upvotes: 2

Elizabeth
Elizabeth

Reputation: 323

Exposed ports needed for another service, if you want to connect two services inside docker, so service with exposed port will be available inside docker net.

Ports property (ports:) make service port available on your host machine, so you can connect it with your OS net.

So you can delete expose property.

Upvotes: 2

Related Questions