0
0
Dockerdevops~3 mins

Why Port mapping with -p flag in Docker? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could open your container app in a browser with just one simple command?

The Scenario

Imagine you run a web app inside a container, but you want to access it from your computer's browser. Without port mapping, you can't reach the app because the container's network is isolated.

The Problem

Manually trying to connect to the container's internal ports is confusing and often fails. You might waste time guessing IPs or opening ports one by one, leading to errors and frustration.

The Solution

The -p flag in Docker lets you easily link a port on your computer to a port inside the container. This way, your app becomes reachable just like any other program on your machine.

Before vs After
Before
docker run myapp
# Can't access app from browser
After
docker run -p 8080:80 myapp
# Access app at http://localhost:8080
What It Enables

It makes your containerized apps accessible from your computer or network effortlessly, bridging the gap between isolated containers and your everyday tools.

Real Life Example

Running a local WordPress site in a container and using -p 8000:80 to open it in your browser at http://localhost:8000 for easy testing and development.

Key Takeaways

Containers isolate apps, so ports must be mapped to access them.

The -p flag connects container ports to your machine's ports.

This makes testing and using container apps simple and direct.