Have you ever written an application that works perfectly on your machine but refuses to work on someone else's?
You tested it locally. Everything was fine.
Then you deployed it to another environment, and suddenly:
- The Java version is different.
- A required library is missing.
- The database version doesn't match.
- An environment variable is not configured.
- The application behaves differently.
And the famous sentence appears:
"But it works on my machine!"
This is one of the problems Docker was designed to solve.
Docker helps us package an application along with the dependencies it needs so that it can run consistently across different environments.
But before understanding Docker, let's understand the problem that existed before it.
Table of Contents
- The problem Docker solves
- The first solution: Virtualization
- Problems with virtualization
- The next solution: Containerization
- Why are containers faster than virtual machines?
- Benefits of containers
- What is Docker?
- Docker components
- Docker architecture
- How Docker runs a container
- Docker container lifecycle
- Basic Docker commands
- Advanced Docker commands
- Run a Java application inside a Docker container
- Multi-container applications
- Docker Compose with Spring Boot and PostgreSQL
- Which Docker concepts should I learn first?
- Common Docker mistakes
- Quick recap
- Try it yourself
The problem Docker solves
Imagine that you have developed a Java application.
Your application requires:
- Java 17
- Spring Boot
- PostgreSQL
- Some external libraries
- Environment variables
- Specific application configurations
Everything works perfectly on your development machine.
Now, you want to deploy the same application to a production server.
But the production server has Java 21 instead of Java 17. PostgreSQL is not installed, and some environment variables are missing.
Your application might fail even though your code is correct.
Why?
Because an application does not depend only on its source code. It also depends on its runtime environment.
The environment includes:
- Operating system
- Runtime versions
- Installed libraries
- Configuration
- Other dependencies
This creates a problem: How can we make sure that our application gets the environment it needs wherever it runs?
Let's look at the first solution.
The first solution: Virtualization
Before containers became popular, virtualization was a common way to isolate applications and their environments.
Virtualization allows us to create multiple virtual machines on a single physical machine.
Each virtual machine behaves like an independent computer.
For example, imagine you have one physical computer running Windows.
You can create:
- Virtual Machine 1: Ubuntu
- Virtual Machine 2: Windows Server
- Virtual Machine 3: Another Linux distribution
Each virtual machine has its own operating system and can run its own applications.
How does virtualization work?
A software layer called a Hypervisor is responsible for creating and managing virtual machines.
It allocates physical resources such as:
- CPU
- RAM
- Storage
- Network resources
Each virtual machine gets a portion of these resources.
+--------------------------------------------------+
| Physical Hardware |
| |
| CPU | RAM | Storage |
+--------------------------------------------------+
|
v
+--------------------------------------------------+
| Hypervisor |
+--------------------------------------------------+
| | |
v v v
+----------------+ +----------------+ +----------------+
| Virtual | | Virtual | | Virtual |
| Machine 1 | | Machine 2 | | Machine 3 |
| | | | | |
| Ubuntu | | Windows Server | | Linux |
| | | | | |
| Application | | Application | | Application |
+----------------+ +----------------+ +----------------+
Notice something important.
Every virtual machine has its own operating system, including its own kernel.
That is where the resource overhead comes from.
Problems with virtualization
Virtualization solves the isolation problem, but it introduces some additional overhead.
Let's understand why.
1. Every virtual machine needs an operating system
Suppose you want to run three small applications.
Using virtualization, you might create three separate virtual machines.
Each VM requires its own operating system, system services, and resources.
Even if the application itself is small, the operating system consumes memory and storage.
2. More resource consumption
Every virtual machine consumes a portion of the physical machine's resources.
For example:
Physical Machine: 16 GB RAM
+----------------------------------+
| Hypervisor |
+----------------------------------+
| VM 1: Ubuntu -> 4 GB RAM |
| VM 2: Ubuntu -> 4 GB RAM |
| VM 3: Windows -> 4 GB RAM |
+----------------------------------+
| Remaining RAM -> 4 GB |
+----------------------------------+
These are illustrative numbers, but they show the idea.
The operating systems themselves require resources before the applications even start.
3. Slower startup
A virtual machine needs to boot its operating system.
It must initialize system services, load the kernel, and prepare the environment.
That takes more time than starting an ordinary isolated application process.
4. More maintenance
You need to manage:
- Operating system updates
- Security patches
- System configurations
- Runtime installations
- Storage and memory allocation
Managing many virtual machines can become complicated.
So, virtualization is useful, but what if we could isolate applications without running a separate operating system for every application?
That brings us to containerization.
The next solution: Containerization
Containerization is an approach where applications run inside isolated environments called containers.
Unlike virtual machines, containers do not normally require a separate guest operating system for each application.
Instead, containers share the host operating system's kernel while maintaining isolation between their processes and resources.
Think of it like this:
A virtual machine is like giving every person an entire house.
A container is like giving every person a separate room in the same building.
Each person has their own space, but the building's common infrastructure is shared.
How does containerization work?
+--------------------------------------------------+
| Physical Hardware |
| |
| CPU | RAM | Storage |
+--------------------------------------------------+
|
v
+--------------------------------------------------+
| Host Operating System |
| |
| +----------------+ +----------------+ |
| | Container 1 | | Container 2 | |
| | | | | |
| | Java App | | Node.js App | |
| | Java Runtime | | Node Runtime | |
| +----------------+ +----------------+ |
| |
| +----------------+ |
| | Container 3 | |
| | | |
| | Python App | |
| | Python Runtime | |
| +----------------+ |
+--------------------------------------------------+
Each container gets an isolated view of its environment, but the containers share the host kernel.
For example:
- Container 1 runs a Java application.
- Container 2 runs a Node.js application.
- Container 3 runs a Python application.
All three can run on the same machine without requiring three separate guest operating systems.
Important: Containers still need a compatible host kernel. On Windows and macOS, Docker Desktop commonly runs Linux containers inside a lightweight Linux virtual machine.
Why are containers faster than virtual machines?
The main reason is that containers do not need to boot a complete guest operating system.
Let's compare their execution models.
Virtual machine
Application
|
Guest Operating System
|
Virtual Hardware
|
Hypervisor
|
Physical Hardware
Container
Application
|
Container Runtime / Isolation
|
Host Operating System Kernel
|
Physical Hardware
A container is essentially an isolated group of processes.
It uses operating-system features such as:
- Namespaces: Provide isolation for processes, networking, mounts, and other resources.
- Control Groups (cgroups): Help limit and account for resource usage such as CPU and memory.
Since the container does not boot another complete operating system, it generally starts much faster and consumes fewer resources than a comparable VM.
| Feature | Virtual Machine | Container |
|---|---|---|
| Operating system | Separate guest OS | Shares host kernel |
| Startup | Generally slower | Generally faster |
| Resource usage | Higher overhead | Lower overhead |
| Isolation | Hardware virtualization boundary | OS-level isolation |
| Portability | Depends on VM image and hypervisor | Depends on image and compatible runtime |
Neither approach replaces the other.
Virtual machines provide a stronger isolation boundary in many configurations. Containers are lightweight and convenient for packaging and deploying applications.
In real-world systems, you will often find containers running inside virtual machines.
Benefits of containers
Now that we understand containerization, let's look at why developers use it.
1. Isolation
Each container runs in an isolated environment.
For example, imagine two applications:
- Application A requires Java 17.
- Application B requires Java 21.
Installing both versions directly on the same machine can introduce configuration conflicts.
With containers, each application can have its own runtime and dependencies.
+----------------------+ +----------------------+
| Container A | | Container B |
| | | |
| Java 17 | | Java 21 |
| Spring Boot App | | Java App |
+----------------------+ +----------------------+
They can run independently without requiring the same Java version.
2. Fast startup
Containers don't need to boot a complete guest operating system.
They start as isolated processes, so their startup is generally much faster than starting a virtual machine.
This is useful when:
- Deploying applications frequently.
- Running automated tests.
- Creating temporary development environments.
- Scaling application instances.
3. Security
Containers provide isolation between applications.
Namespaces, cgroups, Linux capabilities, security profiles, and other kernel features help restrict what a container can access.
For example, a container can be configured to:
- Run as a non-root user.
- Use limited CPU and memory.
- Have restricted filesystem access.
- Drop unnecessary Linux capabilities.
However, remember that containers are not automatically secure.
They share the host kernel, so a kernel vulnerability or incorrect container configuration can affect the security of the host.
4. Portability
Suppose you develop a Java application on your laptop.
You package it into a Docker image.
That image can be used in other environments that support the required container runtime and platform.
For example:
Developer Laptop
|
v
Docker Image
|
+------------------+
| |
v v
Test Server Production Server
| |
v v
Container Container
You don't have to manually install every dependency on each machine.
5. Scalability
Suppose your application receives more traffic than usual.
You can start additional container instances to handle the increased workload.
Incoming Requests
|
v
Load Balancer
/ | \
/ | \
v v v
App 1 App 2 App 3
More instances can handle more requests, provided the application and its supporting infrastructure are designed for scaling.
Docker makes it easier to create and manage these instances.
6. Consistency
A container image packages the application and its required runtime dependencies.
This helps keep the environment consistent across:
- Development
- Testing
- Staging
- Production
The goal is simple:
Build once and use the same image across environments.
Environment-specific settings, such as database credentials, should still be supplied separately through configuration.
What is Docker?
Docker is a platform that helps developers build, package, distribute, and run applications using containers.
Instead of manually installing all the dependencies required by an application, we can define its environment and build a Docker image.
That image can then be used to create containers.
For example, imagine you have a Spring Boot application.
You can package:
- A compatible Java runtime
- Your application JAR
- Required files
- Startup configuration
into a Docker image.
Then you can use that image to create and run a container.
Docker makes containerization easier by providing tools to build, manage, run, and distribute containers.
Docker components
Let's understand the important components of Docker one by one.
1. Docker Engine
Docker Engine is the core technology responsible for building and running containers.
It follows a client-server architecture.
It contains three important parts:
- Docker Client
- Docker Daemon
- Docker REST API
We will understand the complete architecture in a separate section.
For now, remember:
Docker Engine manages Docker objects such as images, containers, networks, and volumes.
2. Container
A container is a running instance of a Docker image.
Think about a class and an object in Java.
class Car {
String model;
}
The class defines the structure, while an object is an actual instance created from that class.
Similarly:
- Docker Image = Template
- Docker Container = Running instance created from that image
For example, you can create multiple containers from the same image.
Docker Image
|
+--------+--------+
| | |
v v v
App 1 App 2 App 3
Container Container Container
Each container has its own writable layer and runtime configuration.
3. Docker Image
A Docker image is a read-only template used to create containers.
It contains the filesystem and configuration required to run an application.
For example, a Java application image may contain:
- A Java runtime
- Application JAR
- Required libraries
- Startup command
Images are built using layers.
For example:
+----------------------------+
| Application JAR |
+----------------------------+
| Application Dependencies |
+----------------------------+
| Java Runtime |
+----------------------------+
| Base Operating System Files|
+----------------------------+
These layers can be reused across images, which helps reduce duplication and makes image distribution more efficient.
4. Dockerfile
A Dockerfile is a text file containing instructions to build a Docker image.
Instead of manually configuring an environment, we write instructions in a Dockerfile.
Example:
FROM eclipse-temurin:17-jre
WORKDIR /app
COPY target/demo.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
Let's understand each instruction.
-
FROM: Specifies the base image. -
WORKDIR: Sets the working directory inside the image. -
COPY: Copies the application JAR into the image. -
EXPOSE: Documents the port the application listens on. -
ENTRYPOINT: Defines the command that runs when the container starts.
We will use this Dockerfile later to run a Java application.
5. Docker Hub
Docker Hub is a cloud-based registry where developers can find, store, and share Docker images.
Think of it like GitHub, but for Docker images.
For example, you can find images for:
- PostgreSQL
- MySQL
- Redis
- Nginx
- Ubuntu
- Java runtimes
You can pull an image from Docker Hub and use it to create a container.
Example:
docker pull postgres
This downloads the PostgreSQL image to your local machine.
You can also publish your own images to a registry.
Docker Hub is a public registry by default for publicly shared images, but it also supports private repositories.
6. Docker Networking
Networking allows containers to communicate with:
- Other containers
- The host machine
- External services
For example, imagine you have two containers:
- One runs a Spring Boot application.
- Another runs PostgreSQL.
The Spring Boot application needs to communicate with PostgreSQL.
Docker networking provides the connection between them.
Docker supports different network drivers, including:
bridgehostnoneoverlaymacvlan
For beginners, the most important one to understand is bridge.
A user-defined bridge network allows containers to communicate using their container names.
Example:
docker network create my-network
Run a PostgreSQL container on that network:
docker run -d \
--name my-postgres \
--network my-network \
postgres
Another container connected to my-network can use my-postgres as the hostname.
7. Docker Volumes
Here is a problem.
Suppose you are running a PostgreSQL database inside a container.
You insert 100 records.
Now imagine that you remove the container.
What happens to the data?
The container's writable filesystem is removed with the container. Without persistent storage, your database data can be lost.
This is where Docker Volumes help.
A volume allows data to persist independently of a container's lifecycle.
+---------------------------+
| PostgreSQL Container |
| |
| Database Process |
| | |
+-------------|-------------+
|
v
+---------------------------+
| Docker Volume |
| |
| Database Data |
+---------------------------+
Even if you remove and recreate the container, the data in the volume can remain available.
Example:
docker volume create postgres-data
Use the volume while running PostgreSQL:
docker run -d \
--name my-postgres \
-e POSTGRES_PASSWORD=secret \
-v postgres-data:/var/lib/postgresql/data \
postgres
Here:
-
postgres-datais the Docker volume. -
/var/lib/postgresql/datais the data directory inside the PostgreSQL container.
Important: A volume is different from a container's writable layer. It is managed separately by Docker.
8. Docker Compose
So far, we have discussed running individual containers.
But real applications usually contain multiple services.
For example, a Spring Boot application might require:
- Spring Boot application
- PostgreSQL database
- Redis cache
- Nginx reverse proxy
Running and configuring each container manually can become repetitive.
Docker Compose solves this problem.
Docker Compose allows us to define and manage a multi-container application using a YAML configuration file.
Instead of running multiple docker run commands, we define the services in one file, usually named compose.yaml.
Example:
services:
app:
image: my-spring-app
ports:
- "8080:8080"
depends_on:
- postgres
postgres:
image: postgres:17
environment:
POSTGRES_USER: admin
POSTGRES_PASSWORD: secret
POSTGRES_DB: mydb
Now we can start the services using:
docker compose up -d
And stop them using:
docker compose down
We will build a more complete example later.
Docker architecture
Now let's understand how all the Docker components communicate with each other.
Docker follows a client-server architecture.
There are three important parts:
- Docker Client
- Docker REST API
- Docker Daemon
Docker Client
The Docker Client is the interface through which we interact with Docker.
Usually, we use the Docker CLI in the terminal.
For example:
docker run nginx
When you execute this command, the Docker Client sends a request to the Docker Daemon.
Docker REST API
The Docker REST API provides an interface through which the Docker Client communicates with the Docker Daemon.
The client and daemon can communicate using a local socket or a network connection.
Docker Daemon
The Docker Daemon is a background process named dockerd.
It is responsible for managing Docker objects.
For example:
- Images
- Containers
- Networks
- Volumes
When the daemon receives a request to run a container, it handles the necessary operations.
Docker architecture diagram
+---------------------------+
| User |
+---------------------------+
|
v
+---------------------------+
| Docker Client |
| |
| docker CLI |
+---------------------------+
|
| Docker API
v
+-------------------------------------------+
| Docker Engine |
| |
| +-------------------------------------+ |
| | Docker Daemon | |
| | dockerd | |
| +-------------------------------------+ |
| |
| +-------------+ +------------------+ |
| | Images | | Containers | |
| +-------------+ +------------------+ |
| |
| +-------------+ +------------------+ |
| | Networks | | Volumes | |
| +-------------+ +------------------+ |
| |
+-------------------------------------------+
|
| Pull / Push
v
+-------------------------------------------+
| Registry |
| |
| +------------------+ +----------------+ |
| | Public Registry | | Private | |
| | | | Registry | |
| +------------------+ +----------------+ |
+-------------------------------------------+
The registry is where images are stored and distributed.
Docker Hub is one example of a registry.
You can also use private registries provided by cloud platforms or organizations.
Local and remote images
An image can exist in two places:
Local image: An image already downloaded or built on your machine.
Remote image: An image stored in a registry.
For example:
docker pull nginx
This downloads the image from a registry to your local image storage.
And:
docker push username/my-image
This uploads your image to a registry, assuming you have the required authentication and permissions.
How Docker runs a container
Let's understand what happens when you execute:
docker run nginx
Docker performs several operations.
- It checks whether the required image is available locally.
- If the image is missing, Docker pulls it from the configured registry.
- Docker creates a container from that image.
- It prepares the container's filesystem and configuration.
- It connects the container to a network.
- It starts the container's main process.
The important thing to understand is that docker run combines container creation and startup.
You don't need to execute every operation manually.
Docker container lifecycle
A container does not simply exist in a running or deleted state.
It goes through different lifecycle states.
Let's understand them.
1. Search
Before downloading an image, you can search for available images.
docker search nginx
This searches Docker Hub for matching images.
2. Pull
Download an image from a registry.
docker pull nginx
3. Create
Create a container from an image without starting it.
docker create --name my-nginx nginx
The container is created but is not running yet.
4. Start
Start an existing stopped container.
docker start my-nginx
5. Stop
Stop a running container gracefully.
docker stop my-nginx
Docker sends a termination signal and allows the main process some time to exit before forcing termination if necessary.
6. Pause
Pause the processes inside a running container.
docker pause my-nginx
To resume them:
docker unpause my-nginx
Remember:
-
stopterminates the container's running process. -
pausetemporarily freezes its processes.
7. Remove container
Remove a stopped container.
docker rm my-nginx
To forcefully remove a running container:
docker rm -f my-nginx
8. Remove image
Remove an image from local storage.
docker rmi nginx
You generally need to remove containers that depend on an image before removing that image.
Basic Docker commands
Let's collect the commands you will use regularly.
Image commands
# Search for an image
docker search nginx
# Download an image
docker pull nginx
# List local images
docker images
# Build an image
docker build -t my-app .
# Remove an image
docker rmi nginx
Container commands
# Create and start a container
docker run nginx
# Run in detached mode
docker run -d nginx
# Run with a custom name
docker run -d --name my-nginx nginx
# List running containers
docker ps
# List all containers
docker ps -a
# Stop a container
docker stop my-nginx
# Start a stopped container
docker start my-nginx
# Restart a container
docker restart my-nginx
# Remove a container
docker rm my-nginx
Port mapping
Suppose your application runs on port 8080 inside a container.
You want to access it using port 8080 on your machine.
Use:
docker run -d -p 8080:8080 my-app
The format is:
HOST_PORT : CONTAINER_PORT
For example:
docker run -d -p 9090:8080 my-app
Now you access the application through port 9090 on your host machine, while the application listens on port 8080 inside the container.
Container inspection commands
# View container logs
docker logs my-nginx
# Follow logs continuously
docker logs -f my-nginx
# Execute a command inside a running container
docker exec -it my-nginx sh
# Inspect container details
docker inspect my-nginx
# View resource usage
docker stats
Volume commands
# Create a volume
docker volume create my-volume
# List volumes
docker volume ls
# Inspect a volume
docker volume inspect my-volume
# Remove a volume
docker volume rm my-volume
Network commands
# List networks
docker network ls
# Create a network
docker network create my-network
# Inspect a network
docker network inspect my-network
# Remove a network
docker network rm my-network
Advanced Docker commands
Once you understand the basics, these commands become useful when debugging and managing applications.
1. View container resource usage
docker stats
Shows live resource usage, including:
- CPU usage
- Memory usage
- Network I/O
- Block I/O
2. View processes inside a container
docker top my-nginx
Displays processes running inside the container.
3. Copy files between host and container
Copy a file from your machine into a container:
docker cp app.properties my-nginx:/app/app.properties
Copy a file from a container to your machine:
docker cp my-nginx:/app/app.properties ./app.properties
4. Inspect image details
docker image inspect nginx
This displays detailed information about the image, including configuration and layers.
5. Remove unused resources
# Remove unused containers
docker container prune
# Remove unused images
docker image prune
# Remove unused volumes
docker volume prune
# Remove unused networks
docker network prune
# Remove unused Docker resources
docker system prune
Be careful with prune commands. They remove resources that Docker considers unused. Review what will be deleted before using them, especially on machines containing important data.
6. Build an image without using the build cache
docker build --no-cache -t my-app .
Useful when you want Docker to execute build steps without reusing cached layers.
7. View Docker disk usage
docker system df
Displays how much disk space Docker is using.
Run a Java application inside a Docker container
Now let's apply what we have learned.
Suppose you have a Spring Boot application that produces a JAR file.
For example:
my-spring-app/
|
+-- src/
|
+-- pom.xml
|
+-- target/
|
+-- demo.jar
Our goal is to run this Java application inside a Docker container.
Step 1: Get a Java runtime
Our application is a Java application, so the container needs a compatible Java runtime.
For running an already-built JAR, a JRE-based image is generally sufficient.
We do not need a full JDK unless we also want to compile Java code inside the image.
For example, we can use:
eclipse-temurin:17-jre
This provides a Java 17 runtime.
Step 2: Copy the JAR into the container image
We need to define how the Docker image should be created.
Create a file named Dockerfile in the project root.
FROM eclipse-temurin:17-jre
WORKDIR /app
COPY target/demo.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
Let's understand the process.
-
FROMselects the Java runtime image. -
WORKDIRcreates and selects/appas the working directory. -
COPYcopies the JAR into the image. -
EXPOSEdocuments that the application uses port 8080. -
ENTRYPOINTdefines the command used to start the application.
Step 3: Create the Docker image
First, build the Spring Boot JAR.
mvn clean package
Then build the Docker image.
docker build -t my-spring-app .
Here:
-
docker buildbuilds an image. -
-tassigns a name to the image. -
my-spring-appis the image name. -
.specifies the build context (the current directory).
Check whether the image was created:
docker images
Step 4: Create and run the container
docker run -d \
--name my-java-container \
-p 8080:8080 \
my-spring-app
Now your Spring Boot application is running inside a container.
Check the container:
docker ps
View the application logs:
docker logs -f my-java-container
Open:
http://localhost:8080
Your Java application is now running inside Docker!
Multi-container applications
In real-world applications, the backend is rarely the only component.
For example, consider a Spring Boot application that uses PostgreSQL.
We need at least two services:
- Spring Boot application
- PostgreSQL database
Traditionally, we would install and configure both separately.
With Docker, we can run them as separate containers.
+---------------------------------------+
| Docker Host |
| |
| +------------------+ |
| | App Container | |
| | | |
| | Spring Boot | |
| +------------------+ |
| | |
| | |
| +---------v--------+ |
| | PostgreSQL | |
| | Container | |
| | | |
| | Database | |
| +------------------+ |
| |
+---------------------------------------+
But how do these containers communicate?
How do we persist database data?
How do we start both containers together?
Let's solve these problems using Docker Compose.
Docker Compose with Spring Boot and PostgreSQL
Docker Compose allows us to define the services, networks, and volumes required by our application in a single YAML file.
For this example, we will use:
Application: Spring Boot
Database: PostgreSQL
Network: Bridge
Volume: postgres-data
Step 1: Understand the services
We have two services.
app
Runs our Spring Boot application.
postgres
Runs our PostgreSQL database.
Each service will run in its own container.
Step 2: Understand the network
Our Spring Boot application needs to communicate with PostgreSQL.
We will create a user-defined bridge network.
networks:
s-network:
driver: bridge
Both containers will connect to this network.
One important benefit is that Docker Compose provides service-name-based DNS discovery on its default or user-defined network.
That means our Spring Boot application can connect to PostgreSQL using:
postgres
as the hostname.
We do not need to hardcode the database container's IP address.
Step 3: Understand the volume
PostgreSQL stores database files inside its container.
If the container is removed, its writable filesystem is removed too.
We need persistent storage.
volumes:
postgres-data:
This creates a named Docker volume.
We will mount it at PostgreSQL's data directory:
/var/lib/postgresql/data
Now database data can survive container replacement, as long as we keep the volume.
Step 4: Create the Compose file
Create a file named compose.yaml in your project directory.
services:
app:
build: .
container_name: spring-app
ports:
- "8080:8080"
depends_on:
postgres:
condition: service_healthy
environment:
SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/mydb
SPRING_DATASOURCE_USERNAME: admin
SPRING_DATASOURCE_PASSWORD: secret
networks:
- s-network
postgres:
image: postgres:17
container_name: postgres-db
environment:
POSTGRES_USER: admin
POSTGRES_PASSWORD: secret
POSTGRES_DB: mydb
volumes:
- postgres-data:/var/lib/postgresql/data
networks:
- s-network
healthcheck:
test: ["CMD-SHELL", "pg_isready -U admin -d mydb"]
interval: 5s
timeout: 5s
retries: 5
networks:
s-network:
driver: bridge
volumes:
postgres-data:
Let's understand the important parts.
Services
services:
app:
postgres:
We have defined two services.
Build
build: .
Docker Compose builds the application image using the Dockerfile in the current directory.
Ports
ports:
- "8080:8080"
Maps host port 8080 to container port 8080.
Environment variables
environment:
SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/mydb
This configures the Spring Boot application to connect to PostgreSQL.
Notice the hostname:
postgres
That is the Compose service name, not localhost.
Inside the application container, localhost refers to the application container itself, not the PostgreSQL container.
depends_on
depends_on:
postgres:
condition: service_healthy
This tells Compose to wait for PostgreSQL's health check to pass before starting the application service.
Without a health check condition, basic depends_on controls startup order but does not necessarily mean the database is ready to accept connections.
Volumes
volumes:
- postgres-data:/var/lib/postgresql/data
Connects the named volume to PostgreSQL's data directory.
Networks
networks:
- s-network
Connects both services to the same bridge network.
Step 5: Run the application
Start both services:
docker compose up -d
Docker Compose will:
- Build the Spring Boot image.
- Pull the PostgreSQL image if needed.
- Create the network.
- Create the volume.
- Create both containers.
- Start PostgreSQL.
- Wait for the PostgreSQL health check.
- Start the Spring Boot application.
Check the containers:
docker compose ps
View application logs:
docker compose logs -f app
View PostgreSQL logs:
docker compose logs -f postgres
Step 6: Stop the application
To stop and remove the containers and the Compose-created network:
docker compose down
Our named volume remains available.
That means the PostgreSQL data can still be used when we start the application again.
If you also want to remove the named volume:
docker compose down -v
Be careful: This removes the database volume and its persisted data.
Final architecture
Let's visualize everything we created.
+------------------------------------------------------+
| Docker Host |
| |
| +------------------------------------------------+ |
| | s-network (bridge) | |
| | | |
| | +----------------------+ | |
| | | App Container | | |
| | | | | |
| | | Spring Boot | | |
| | | Port: 8080 | | |
| | +----------+-----------+ | |
| | | | |
| | | JDBC Connection | |
| | | | |
| | +----------v-----------+ | |
| | | PostgreSQL Container | | |
| | | | | |
| | | PostgreSQL | | |
| | | Port: 5432 | | |
| | +----------+-----------+ | |
| | | | |
| +-------------|----------------------------------+ |
| | |
| v |
| +-----------------------------------------------+ |
| | postgres-data | |
| | Docker Volume | |
| +-----------------------------------------------+ |
| |
+------------------------------------------------------+
Now we have:
- Two independent containers.
- One bridge network.
- One persistent volume.
- One Compose file to manage everything.
This is the basic idea behind a multi-container Docker application.
Which Docker concepts should I learn first?
If you are new to Docker, don't try to learn every command at once.
Start with the concepts that explain how Docker works.
My recommended learning order:
- Understand the problem Docker solves.
- Understand virtual machines versus containers.
- Learn Docker images and containers.
- Learn Dockerfile instructions.
- Practice
docker pull,docker run,docker ps, anddocker stop. - Understand port mapping.
- Learn volumes.
- Learn bridge networking.
- Understand Docker architecture.
- Learn Docker Compose.
Once you understand these, move towards image optimization, multi-stage builds, security, and container orchestration.
Common Docker mistakes
1. Confusing an image with a container
An image is a template, while a container is an instance created from that image.
You can create multiple containers from one image.
How to avoid it: Remember: Image = Template, Container = Instance.
2. Thinking container data is always persistent
Files written to a container's writable layer can disappear when the container is removed.
How to avoid it: Use Docker volumes or bind mounts for data that must survive container replacement.
3. Using localhost to connect to another container
Inside a container, localhost refers to that same container.
It does not automatically refer to another container.
How to avoid it: Connect containers through a shared network and use the other container's service name.
4. Assuming EXPOSE publishes a port
The Dockerfile instruction EXPOSE documents the port an application listens on.
It does not publish that port to the host machine.
How to avoid it: Use -p HOST_PORT:CONTAINER_PORT when running a container.
5. Assuming containers are completely isolated
Containers share the host kernel. Their isolation depends on operating-system features and configuration.
How to avoid it: Use least privilege, non-root users, resource limits, and appropriate security settings.
6. Removing volumes accidentally
Running:
docker compose down -v
removes the Compose-managed named volumes as well.
This can delete your database data.
How to avoid it: Understand the difference between docker compose down and docker compose down -v before using them.
Quick recap
- Docker helps package and run applications in containers.
- Virtual machines run separate guest operating systems.
- Containers share the host kernel and provide OS-level isolation.
- Containers generally start faster because they don't boot a complete guest OS.
- Docker Engine manages images, containers, networks, and volumes.
- An image is a template used to create containers.
- A Dockerfile contains instructions for building an image.
- Docker Hub is a registry for sharing and distributing images.
- Docker networking allows containers to communicate.
- Docker volumes provide persistent storage.
- Docker Compose manages multi-container applications.
- A Spring Boot application and PostgreSQL database can run in separate containers and communicate over a bridge network.
Try it yourself
Don't stop after reading the commands. Try these exercises.
Practice 1: Basic Docker
- Pull the Nginx image.
- Create a container named
my-nginx. - Map host port 8080 to container port 80.
- Open
http://localhost:8080. - View its logs.
- Stop the container.
- Start it again.
- Remove the container.
Practice 2: Docker images
- Create a simple Java application.
- Build its JAR file.
- Write a Dockerfile.
- Build an image.
- Run a container using that image.
- Inspect the image and container.
Practice 3: Docker Compose
- Create a Spring Boot application.
- Create a PostgreSQL service using Docker Compose.
- Connect both services through a bridge network.
- Add a named volume for PostgreSQL.
- Start both services using
docker compose up -d. - Insert some records into PostgreSQL.
- Run
docker compose down. - Start everything again and verify that the records still exist.
Bonus challenge: Modify the Compose file to add a Redis container and connect your Spring Boot application to it.
If this helped, or if you spotted something I should fix, tell me in the comments. I'm still learning too.
Top comments (0)