Software Consulting Services
software de gesstion de recursos

How to do dockerfile port mapping?

April 08, 2025

Tags: Technologies
dockerfile port mapping

 

If you're working with Docker and wondering how to map ports from a Dockerfile, let's be clear right away: you can't map ports directly in the Dockerfile. What you can do is expose the port that your application will use inside the container. The actual port mapping is done outside the Dockerfile, when running the container.

 

Here’s a typical example. Suppose you have a Node.js app running on port 3000. Your Dockerfile might look like this:

 

FROM node:18
WORKDIR /app
COPY . .
RUN npm install
EXPOSE 3000
CMD ["npm", "start"]

 

The line EXPOSE 3000 doesn’t perform the mapping. It simply tells Docker that the container can listen on port 3000. It’s a way to document expected behavior and assist automated tools—but it doesn’t expose the port to the outside world on its own.

 

The real mapping happens when you run the container, like this:

 

docker build -t my-app .
docker run -p 8080:3000 my-app

 

With -p 8080:3000, you're telling Docker to route traffic from port 8080 on the host to port 3000 inside the container. You can now access your app via localhost:8080. Need multiple instances? Just use different host ports:

 

docker run -p 8081:3000 my-app
docker run -p 8082:3000 my-app

 

In more structured environments, like with Docker Compose, you can define port mappings in the configuration file:

version: '3'
services:
  web:
    build: .
    ports:
      - "8080:3000"

 

This sets up port 8080 on the host to connect with port 3000 inside the container—same logic, just declarative.

 

Best practices for dockerfile port mapping

 

only expose what’s necessary, limit access to sensitive services, and use custom Docker networks for multi-container setups. This helps improve security and clarity in your infrastructure.

 

According to the official Docker documentation, EXPOSE is purely informational. Tools like Kubernetes or Docker Swarm may use this metadata to automate networking, but you still need to explicitly define your port mappings.

 

In short: use EXPOSE to document internal ports, and -p or ports: to map them externally.

 

If you're developing a containerized app, make sure it’s set up correctly from the start. At [Your Agency Name], we help teams build Docker environments that are productive, secure, and ready to scale. From architecture design to CI/CD pipelines and Kubernetes automation—we’ve got you covered.

 

Need modern, scalable, and frictionless infrastructure for your project? Let’s talk and take your development to the next level with Docker.