Cloud and infrastructure / Linux, networking, and Docker
Run a service in a container
Use Linux processes, ports, and Docker to understand a deployable unit.
Perkiraan waktu: 35 menit
Learning outcome
By the end of this lesson, you will be able to explain what a container is, run a simple web service in Docker, and understand how ports, processes, and networking work together.
The problem containers solve
"It works on my machine" is a running joke among developers. Your Python app runs fine on your laptop but crashes on your friend's computer because the Python version is different, or a library is missing, or the file paths use different slashes.
Containers solve this by packaging your application with everything it needs.
flowchart TD
A[Browser] -->|HTTP request on port 8080| B[Docker host]
subgraph C[Container]
D[Your app]
E[Python 3.12]
F[Libraries]
G[Files]
end
B --> C
C -->|port 8080| A
What is a container?
A container is a lightweight, isolated environment that runs your application. It shares the host computer's operating system kernel (unlike a virtual machine, which runs a full OS), so it starts in seconds.
Think of it like a shipping container for code. A shipping container has the same dimensions whether it is on a ship, a train, or a truck. Your app container runs the same on your laptop, your team-mate's computer, and a cloud server.
Your first container
Create a file called Dockerfile:
FROM python:3.12-slim
WORKDIR /app
COPY . .
RUN pip install flask
CMD ["python", "app.py"]
Build and run:
docker build -t my-app .
docker run -p 8080:5000 my-app
Now visit http://localhost:8080. Your app is running in a container.
Ports explained
The -p 8080:5000 maps port 8080 on your computer to port 5000 inside the container. The container thinks it is using port 5000. The outside world accesses it through port 8080.
Common beginner mistakes
- Forgetting the port mapping. Without
-p, the container runs but you cannot reach it from your browser. - Building the image every time you change code. Use
docker run -v $(pwd):/appto mount your code directory so changes are reflected instantly during development. - Putting secrets in the image. Never hardcode passwords or API keys in a Dockerfile. Use environment variables at runtime.
Practice task
Take the Flask app you built in a previous lesson. Write a Dockerfile for it. Build the image, run the container, and verify you can reach it in your browser.
Recap
- Containers package your app with its environment so it runs everywhere.
- Docker builds images from a Dockerfile and runs them as containers.
- Port mapping connects container ports to host ports.
- Containers start quickly because they share the host kernel.
Next step
Now that you can run a service in a container, the next lesson compares cloud services so you can choose the right platform for your project.