Urgent.News

What's breaking now, across thousands of outlets.

Tech

How Docker maps a containerized port to your local machine?

When you spin up a database inside a Docker container, you are essentially launching an entirely isolated, lightweight operating system that lives inside your physical machine. This isolated environment has its own file system, its own memory limits, and crucially, its own private network. By default, a Docker container is completely sealed off from your local machine (which we refer to as the…

When you launch a database inside a Docker container, it operates as its own isolated environment, separate from your physical machine. This container has its own file system, memory limits, and a private network. Normally, this container is not connected to your local machine, often referred to as the host. For instance, if a PostgreSQL database is running within this container, it would typically listen on the standard port 5432.

However, due to the container’s private network, your Node.js application running on the host cannot interact with this database. The communication is blocked by the container’s network boundary. To enable your Node.js application to reach the PostgreSQL database, we must create a connection pathway through a process known as Port Forwarding or Port Mapping.

This mechanism allows us to define a rule that connects the host port to the container port in a specific manner, typically expressed as Host Port: Container Port. For example, mapping 5432:5432 tells Docker to listen on port 5432 on your actual laptop and then forward any traffic received on that port directly into the container's internal port 5432.

Mapping ports instead of directly exposing the container is beneficial for several reasons. Firstly, it resolves conflicts, such as when another version of PostgreSQL is already installed on your laptop and is using port 5432. Secondly, it enhances security by implementing the principle of least privilege, ensuring that only the specified ports are accessible from outside the container.

This setup allows for a clean, controlled environment where the container can run independently without affecting or being affected by applications on your host machine. Once you are finished with the containerized application, you simply stop the container, and your host machine remains unaffected.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

More from Sunday 27 September →