Nono.MA

Bind a port from Docker to your machine

MARCH 17, 2023

docker run -it -p HOST_PORT:CONTAINER_PORT your-image

When you run services inside of Docker in specific ports, those are internal ports on the virtual container environment. If you want to connect to those services from your machine, you need to expose ports to the outside world explicitly. In short, you need to map TCP ports in the container to ports on the Docker host, which may be your computer. Here's how to do it.

Let's imagine we have a Next.js app running inside our Docker container.

› docker run -it my-app-image
next dev
# ready - started server on 0.0.0.0:3000, url: http://localhost:3000

The site is exposed to port 3000 of the container, but we can't access it from our machine at http://localhost:3000. Let's map the port.

› docker run -it -p 1234:3000 my-app-image
next dev
# ready - started server on 0.0.0.0:3000, url: http://localhost:3000
  • We've mapped TCP port 3000 of the container to port 1234 of the Docker host (our machine)
  • We can now browse the app at http://localhost:1234
  • When your machine loads port 1234, Docker forwards the communication to port 3000 of the container

BlogCodeDockerTil