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.jsBuild the image and name it foo:
docker build -t foo .Start a container from the image:
docker run -d fooThe 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:8000Use 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 fooNow the host exposes port 8000 and forwards requests to port 8000 inside the container:
curl localhost:8000The application responds with:
Hello WorldYou 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 fooThe application still listens on port 8000 inside the container, but the host exposes it on port 8001:
curl localhost:8001When 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:8000Start the application with Compose:
docker-compose up -dThen test the published host port:
curl localhost:8010Docker forwards the request from port 8010 on the host to port 8000 in the container, so the response is:
Hello World
Join the discussion!
Comments
Want to comment on this lesson?
Log in to leave comments.