0

I have created a postgres container from the official posgres image. I am trying to map the port 5432 so I can access the container from my localhost.

If I expose the port through the Dockerfile, the mapping doesn't happen. Here is my Dockerfile

FROM postgres

EXPOSE 5432:5432

When I build the image and run this, here is what I get when I run docker ps it see this in the PORTS column 5432/tcp

When I remove the EXPOSE from the Dockerfile and build this

FROM postgres

And then build the image and pass the port on the command line docker run -p 5432:5432 -d postgres, the port does get mapped. When I run docker ps I see 0.0.0.0:5432->5432/tcp in the PORTS column.

What am I doing wrong? How do I expose the ports in the Dockerfile in a manner that they will get mapped?

jhamm
  • 24,124
  • 39
  • 105
  • 179
  • 2
    Possible duplicate of [Does "ports" on docker-compose.yml have the same effect as EXPOSE on Dockerfile?](https://stackoverflow.com/questions/35548843/does-ports-on-docker-compose-yml-have-the-same-effect-as-expose-on-dockerfile) – rdas Apr 20 '19 at 18:29

1 Answers1

1

If you want to publish the ports defined inside your Dockerfile with the EXPOSE command, you can use the -P flag:

docker run -P <container>

EXPOSE doesn't actually do anything by itself. As mentioned in the Docker documentation:

The EXPOSE instruction informs Docker that the container listens on the specified network ports at runtime.

The EXPOSE instruction does not actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container, about which ports are intended to be published. To actually publish the port when running the container, use the -p flag on docker run to publish and map one or more ports, or the -P flag to publish all exposed ports and map them to high-order ports.

Alassane Ndiaye
  • 4,427
  • 1
  • 10
  • 19