Video Lesson: Expose Docker services with port binding

Expose Docker services with port binding

Learn how to publish container ports and map them to host ports for external access.


Lesson Content

Let’s look at a simple Node.js application that responds with Hello World to every request and starts a web server on port 8000:

// Load the http module to create an http server.
var http = require('http');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");

The Dockerfile copies the application into the image and starts Node.js:

FROM mhart/alpine-node
COPY index.js .
EXPOSE 8000
CMD node index.js

Build the image and name it foo:

docker build -t foo .

Start a container from the image:

docker run -d foo

The application is running inside the container, but Docker locks down container ports by default. If you try to access port 8000 from the host, the connection is refused:

curl localhost:8000

Use the -p option with docker run to publish a container port on the host. The host port comes first, followed by the container port:

docker run -d -p 8000:8000 foo

Now the host exposes port 8000 and forwards requests to port 8000 inside the container:

curl localhost:8000

The application responds with:

Hello World

You can map the container port to a different host port. This is useful when multiple containers listen on the same port internally:

docker run -d -p 8001:8000 foo

The application still listens on port 8000 inside the container, but the host exposes it on port 8001:

curl localhost:8001

When you use Docker Compose, define the same mapping with the ports option. The host port still comes first, followed by the container port:

version: '3'
services:
  app:
    build: .
    ports:
      - 8010:8000

Start the application with Compose:

docker-compose up -d

Then test the published host port:

curl localhost:8010

Docker forwards the request from port 8010 on the host to port 8000 in the container, so the response is:

Hello World
Maggie

Hey, I'm Maggie! 👋

Ask me anything.

Want to chat with Maggie?

Log in for AI tutor access.

Comments

Join the discussion!

Notes

Keep track of what you learn!