Docker Tutorial for Beginners to Advanced: Complete Guide with Spring Boot, MySQL & Docker Compose
Learn Docker from scratch with simple explanations and practical examples. This guide covers images, containers, Dockerfile, volumes, networking, and Docker Compose — and then builds a complete Spring Boot + MySQL application using Docker Compose.
Have you ever finished a Spring Boot project on your laptop, only to find it doesn't run on your teammate's machine or the server? Maybe the Java version is different. MySQL isn't installed. An environment variable is missing. A dependency behaves differently. These small things can turn a simple deployment into hours of debugging. Docker solves this problem. It lets you package your application and everything it needs into a portable image, which can run as a container on any machine that has Docker installed.
Why Docker Still Matters in Java Development
Have you ever finished a Spring Boot project on your laptop, only to find it won't run on your teammate's machine or the server? Maybe the Java version is different. MySQL isn't installed. An environment variable is missing. A dependency behaves differently. These small things can turn a simple deployment into hours of debugging.
Docker solves this problem. It lets you package your application and everything it needs into a portable image. That image can then run as a container on any machine that has Docker installed.
For Java developers, Docker is especially useful with Spring Boot, MySQL, Redis, Kafka, and microservices. Instead of installing every dependency manually, you run them as containers. In this tutorial, we start with the basics and move step-by-step toward real-world Docker usage. We will also containerize a Spring Boot application and run it with MySQL using Docker Compose.
Whether you are a fresher learning Docker for the first time or an experienced backend developer who wants to understand how Docker fits into modern application development, this guide is written for you.
What Is Docker?
Docker packages your application environment into a reusable image, and containers are running instances created from that image.
Docker is a platform and ecosystem for building, packaging, and running applications in containers. A container packages an application with the files, libraries, and runtime dependencies it needs. Containers share the host operating system kernel while remaining isolated from other processes through operating-system features.
Think about a Spring Boot application that needs:
- Java 17
- Spring Boot dependencies
- Application configuration
- Database connectivity
- Additional runtime libraries
Without containerization, developers often need to configure these dependencies separately on every machine. With Docker, you define how to build the application image and how to run it. Other developers and environments can use the same image rather than repeating the installation process.
The Three Key Ideas
| Term | Meaning | Example |
|---|---|---|
| Image | A read-only template containing the app and its runtime | eclipse-temurin:17-jre |
| Container | A running or stopped instance created from an image | A running Spring Boot API |
| Registry | A service that stores and distributes images | Docker Hub |
Real-World Example
Imagine a company developing a payment application using Spring Boot, MySQL, and Redis. One developer may have MySQL installed locally, another may use a different version, and the testing server may have a different configuration. With Docker Compose, the team can define the application, database, and cache services in one configuration file and start the local environment using a single command.
Why Do We Need Docker?
Before Docker became common in development workflows, teams often spent time preparing servers and machines with matching application runtimes and dependencies. Docker helps make these environments more consistent.
| Without Docker | With Docker |
|---|---|
| Install runtime manually | Use an image with the required runtime |
| Install database locally | Run database as a container |
| Configure every environment separately | Share Dockerfile and Compose configuration |
| Dependency versions may differ | Use explicitly selected image versions |
| Manual environment preparation | Automate environment startup |
| Harder to reproduce issues | Recreate the same container setup |
Virtual Machines vs Docker Containers
Virtual machines and containers both provide isolation, but they work differently. A virtual machine runs its own guest operating system on virtualized hardware. A container shares the host operating system kernel and isolates application processes.
Virtual machines run a guest OS per VM. Containers share the host kernel.
| Feature | Virtual Machine | Container |
|---|---|---|
| Operating system | Guest OS per VM | Shares host kernel |
| Startup | Generally slower | Generally faster |
| Resource usage | Usually higher | Usually lower |
| Isolation | Virtualized hardware boundary | Process and namespace isolation |
| Typical use | Different operating systems and workloads | Application packaging and deployment |
Containers are not miniature virtual machines. They rely on operating-system isolation features, and their security boundaries must be configured properly.
Docker Architecture
Understanding Docker architecture makes it easier to understand how images are built and containers are executed. Docker commonly involves these components:
- Docker Client: The command-line interface used to send commands.
- Docker Daemon: The background service responsible for managing Docker objects.
- Docker Engine API: The API through which clients communicate with the engine.
- Docker Images: Read-only templates used to create containers.
- Docker Containers: Running or stopped instances created from images.
- Docker Registry: A service used to store and distribute images.
The Docker Engine manages images and containers and pulls from a registry when needed.
For example, when you run:
docker run nginx
The Docker client sends a request to the engine. If the required image is not available locally, Docker attempts to pull it from a registry. It then creates and starts a container from that image.
Important Docker Concepts
6.1 Docker Image
A Docker image is a read-only template containing the application and the filesystem layers required to run it. Examples include:
nginx:alpine
mysql:8.4
redis:7
eclipse-temurin:17-jre
Image names generally follow the format:
repository:tag
A tag identifies a particular image version or variant. For repeatable deployments, use deliberate versioning and consider pinning images by digest.
6.2 Docker Container
A container is an instance created from an image. It has its own writable layer and can be started, stopped, inspected, and removed.
docker run -d --name my-nginx -p 8080:80 nginx:alpine
Here:
-druns the container in the background.--nameassigns a readable name.-p 8080:80maps host port 8080 to container port 80.nginx:alpineidentifies the image.
Open http://localhost:8080 in your browser to test it.
6.3 Docker Registry
A registry stores and distributes Docker images. Docker Hub is a widely used public registry, while organizations can also use private registries. Typical workflow:
docker login
docker build -t yourusername/product-api:1.0 .
docker push yourusername/product-api:1.0
Do not push private application images to a public repository unless that is intentional.
Install Docker Desktop on Windows
For Windows developers, Docker Desktop is a convenient way to run Docker locally. It commonly uses the Windows Subsystem for Linux 2 (WSL 2) backend when configured for Linux containers.
Step 1: Check System Requirements
- Supported Windows version
- Hardware virtualization enabled
- WSL 2 support when using the WSL backend
- Enough memory and disk space
- Administrator access for installation and required configuration
Step 2: Install Docker Desktop
Download Docker Desktop from the official website:
Follow the installer instructions and choose the WSL 2 backend when appropriate for your machine.
Step 3: Verify the Installation
Open PowerShell or Windows Terminal and run:
docker --version
docker compose version
docker info
If Docker Desktop is running correctly, these commands should display the Docker client, Compose, and engine information.
Step 4: Run Your First Container
docker run hello-world
Docker downloads the small test image if necessary, creates a container, and runs it. A success message confirms that the Docker client can communicate with the engine and run a container.
Essential Docker Commands Every Developer Should Know
These commands are useful in daily development, testing, and troubleshooting.
Check Docker Information
docker --version
docker info
docker version
Download an Image
docker pull nginx:alpine
List Local Images
docker images
Run a Container
docker run -d --name web-server -p 8080:80 nginx:alpine
List Running Containers
docker ps
List All Containers
docker ps -a
View Container Logs
docker logs web-server
docker logs -f web-server
Inspect a Container
docker inspect web-server
Execute a Command Inside a Container
docker exec -it web-server sh
Some images provide Bash instead of, or in addition to, the shell shown above.
Stop, Start, and Restart a Container
docker stop web-server
docker start web-server
docker restart web-server
Remove a Container
docker rm web-server
A running container must be stopped first unless you explicitly use a force option.
Remove an Image
docker rmi nginx:alpine
View Resource Usage
docker stats
Remove Unused Docker Objects
docker system df
docker system prune
What Is a Dockerfile?
A Dockerfile is a text file containing instructions Docker uses to build an image.
Instead of manually preparing an environment every time, you define the steps once in a Dockerfile. For example, a Spring Boot application needs a Java runtime and an executable JAR. A Dockerfile describes how to create an image containing the runtime and application JAR.
Important Dockerfile Instructions
| Instruction | Purpose |
|---|---|
FROM | Selects the base image. |
WORKDIR | Sets the working directory inside the image. |
COPY | Copies files from the build context. |
ADD | Copies files and supports additional source handling; prefer COPY for ordinary file copies. |
RUN | Executes a command during image building. |
ENV | Defines environment variables in the image. |
ARG | Defines build-time variables. |
EXPOSE | Documents the container port used by the application. |
CMD | Defines the default command when a container starts. |
ENTRYPOINT | Defines the main executable for the container. |
USER | Sets the user for subsequent instructions and runtime. |
LABEL | Adds metadata to an image. |
Simple Dockerfile Example
FROM eclipse-temurin:17-jre
WORKDIR /app
COPY app.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
Let's understand it:
FROMselects a Java 17 runtime image.WORKDIRcreates and selects the application directory.COPYcopies the executable JAR into the image.EXPOSEdocuments the application's container port.ENTRYPOINTstarts the Spring Boot application.
EXPOSE does not publish a port on your computer. Port
publishing is configured using -p with docker run or the ports section in
Docker Compose.
RUN vs CMD vs ENTRYPOINT
This is one of the most frequently asked Docker interview questions.
| Instruction | When it runs | Example |
|---|---|---|
RUN |
During image build | Install a package |
CMD |
When a container starts | Default startup command |
ENTRYPOINT |
When a container starts | Main application executable |
Example:
FROM alpine:3.21
RUN apk add --no-cache curl
CMD ["sh"]
RUN installs curl while building the image. CMD starts a shell when the
container is launched.
For a Spring Boot application, a common pattern is:
ENTRYPOINT ["java", "-jar", "app.jar"]
Build Your First Docker Image
Let's create a small example to understand the build process.
Create a directory named docker-demo.
Inside it, create a file named index.html:
<h1>Hello from Docker!</h1>
<p>My first Docker container is running.</p>
Create a file named Dockerfile:
FROM nginx:alpine
COPY index.html /usr/share/nginx/html/index.html
Open a terminal in the project directory and execute:
docker build -t my-first-image:1.0 .
The dot represents the build context: the directory Docker can access for files used by the build.
Now run the image:
docker run -d \
--name my-first-container \
-p 8080:80 \
my-first-image:1.0
On Windows PowerShell, you can enter the command on one line:
docker run -d --name my-first-container -p 8080:80 my-first-image:1.0
Open http://localhost:8080. You should see the HTML page served by Nginx.
For Beginners: The Shipping Container Analogy
Think of a shipping container. Before standard containers, every cargo item was loaded and unloaded differently depending on the ship, the port, and the cargo type. Standardized containers changed that — a crane, a truck, or a ship only needs to know it is handling a standard container, not what is inside. Docker images work the same way: any machine with Docker can run the image without knowing the details inside. The image is the container. The running container is the container loaded onto a ship, truck, or train.
Docker Image Layers and Build Cache
Docker images are built from layers. Many Dockerfile instructions create filesystem changes that become part of the image. Docker can reuse cached build results when the relevant inputs have not changed. This can make repeated builds faster.
For example, consider this Dockerfile:
FROM eclipse-temurin:17-jdk
WORKDIR /app
COPY . .
RUN ./gradlew clean build
Whenever source files change, the broad COPY instruction can invalidate the later build step and cause Gradle to run again. A more thoughtful Dockerfile separates dependency-related inputs from frequently changing source files. This allows more build steps to be reused.
For production builds, use BuildKit features and a carefully structured multi-stage Dockerfile where appropriate.
Docker Volumes: How to Persist Data
Containers are designed to be replaceable. Data written only to a container's writable layer can be lost when that container is removed. Docker volumes provide a way to persist data independently of a container's lifecycle.
Why Do We Need Volumes?
Imagine you are running MySQL inside a container. You insert customer records and then remove the container. If the database files existed only in the container's writable layer, removing that container could remove those files too. Using a volume keeps the database data separate from the container.
A volume keeps data separate from the container so it survives container removal.
Create a Volume
docker volume create mysql-data
List Volumes
docker volume ls
Inspect a Volume
docker volume inspect mysql-data
Run MySQL with a Volume
docker run -d \
--name mysql-db \
-e MYSQL_ROOT_PASSWORD=local_dev_password \
-e MYSQL_DATABASE=product_db \
-v mysql-data:/var/lib/mysql \
-p 3306:3306 \
mysql:8.4
On Windows PowerShell, use the same command on one line.
Volume vs Bind Mount
| Volume | Bind Mount |
|---|---|
| Managed by Docker | Uses an explicit host filesystem path |
| Useful for persistent application data | Useful for sharing source files |
| Location managed by Docker | Location selected by the developer |
| Can be reused across containers | Depends on host path availability |
For database persistence, named volumes are a common choice. For local source-code development, bind mounts can be useful.
Docker Networking
Docker networking allows containers to communicate with one another and with external systems. For example, a Spring Boot application may need to connect to MySQL and Redis. These services can run in separate containers and communicate over a Docker network.
Common Docker Network Drivers
- bridge: Common for containers running on a single Docker host.
- host: Uses the host network namespace on supported platforms.
- none: Disables normal network connectivity for the container.
- overlay: Supports multi-host container networking in appropriate Docker environments.
Create a Network
docker network create product-network
Run MySQL on the Network
docker run -d \
--name mysql-db \
--network product-network \
-e MYSQL_ROOT_PASSWORD=local_dev_password \
-e MYSQL_DATABASE=product_db \
mysql:8.4
Run an Application on the Same Network
docker run -d \
--name product-api \
--network product-network \
-p 8081:8080 \
-e SPRING_DATASOURCE_URL=jdbc:mysql://mysql-db:3306/product_db \
my-product-api:1.0
Inside the Docker network, the application can use mysql-db as the database hostname
because it is the container name on that user-defined network.
localhost refers to that same container,
not another container and not automatically your Windows host. Use the service name or container
name for container-to-container communication.
What Is Docker Compose?
Docker Compose is a tool for defining and running multi-container applications using a YAML configuration file. Suppose your project needs a Spring Boot application, a MySQL database, and a Redis cache. Without Compose, you may need several long Docker commands and manually configure the network, ports, environment variables, and volumes.
Docker Compose puts this configuration in one file, usually named compose.yaml.
Compose starts multiple services on a shared Docker network.
Useful Docker Compose Commands
docker compose up
docker compose up -d
docker compose down
docker compose ps
docker compose logs
docker compose logs -f app
docker compose build
docker compose restart app
docker compose config
docker compose down removes the Compose containers and networks. Named volumes are
retained unless you explicitly request their removal with -v.
Complete Project: Spring Boot + MySQL with Docker Compose
Now let's build something useful for Java developers. We will create a Spring Boot Product API and run it inside a Docker container. MySQL will run in another container, and both services will communicate through a Compose-managed network.
Project Architecture
REST Client → Spring Boot Container (:8080) → MySQL Container (:3306) → Persistent MySQL Volume
Step 1: Create the Project
Create a Spring Boot project with the following dependencies:
- Spring Web
- Spring Data JPA
- MySQL Driver
Use Java 17 and a compatible Spring Boot 3 release.
Recommended project structure:
docker-springboot-demo/
|
|-- src/
| |-- main/
| |-- java/com/example/product/
| | |-- ProductApplication.java
| | |-- Product.java
| | |-- ProductRepository.java
| | |-- ProductController.java
| |
| |-- resources/
| |-- application.yml
|
|-- gradlew
|-- gradlew.bat
|-- gradle/
|-- build.gradle
|-- Dockerfile
|-- .dockerignore
|-- compose.yaml
Step 2: Configure Gradle
Example build.gradle:
plugins {
id 'java'
id 'org.springframework.boot' version '3.5.5'
id 'io.spring.dependency-management' version '1.1.7'
}
group = 'com.example'
version = '1.0.0'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(17)
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
runtimeOnly 'com.mysql:mysql-connector-j'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}
The versions above are illustrative compatible project settings. For a new project, select currently supported Spring Boot and Gradle versions that match your build environment.
Step 3: Create the Spring Boot Main Class
package com.example.product;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProductApplication {
public static void main(String[] args) {
SpringApplication.run(ProductApplication.class, args);
}
}
Step 4: Create the Product Entity
package com.example.product;
import jakarta.persistence.*;
import java.math.BigDecimal;
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false, precision = 12, scale = 2)
private BigDecimal price;
public Product() {
}
public Product(String name, BigDecimal price) {
this.name = name;
this.price = price;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public BigDecimal getPrice() {
return price;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
}
Step 5: Create the Repository
package com.example.product;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository
extends JpaRepository<Product, Long> {
}
Step 6: Create the REST Controller
package com.example.product;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.List;
@RestController
@RequestMapping("/api/products")
public class ProductController {
private final ProductRepository repository;
public ProductController(ProductRepository repository) {
this.repository = repository;
}
@PostMapping
public Product create(@RequestBody Product product) {
return repository.save(product);
}
@GetMapping
public List<Product> getAll() {
return repository.findAll();
}
@GetMapping("/{id}")
public Product getById(@PathVariable Long id) {
return repository.findById(id)
.orElseThrow(() ->
new RuntimeException("Product not found"));
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
repository.deleteById(id);
}
}
Step 7: Configure application.yml
We will keep database details configurable through environment variables.
server:
port: 8080
spring:
datasource:
url: ${SPRING_DATASOURCE_URL:jdbc:mysql://localhost:3306/product_db}
username: ${SPRING_DATASOURCE_USERNAME:product_user}
password: ${SPRING_DATASOURCE_PASSWORD:local_dev_password}
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
The fallback values are for local learning only. Production deployments should inject credentials securely and use database migration tools rather than automatic schema updates.
Step 8: Build the Spring Boot JAR
Before creating the Docker image, verify that the application builds successfully.
On Windows:
gradlew.bat clean bootJar
On Linux or macOS:
./gradlew clean bootJar
The executable JAR will normally be generated inside:
build/libs/
Step 9: Create a Multi-Stage Dockerfile
Now create a file named Dockerfile in the project root.
# Stage 1: Build the application
FROM eclipse-temurin:17-jdk-jammy AS builder
WORKDIR /app
COPY gradlew .
COPY gradle gradle
COPY build.gradle settings.gradle ./
RUN chmod +x gradlew
COPY src src
RUN ./gradlew bootJar --no-daemon
# Stage 2: Run the application
FROM eclipse-temurin:17-jre-jammy
WORKDIR /app
RUN useradd --system --uid 10001 appuser
COPY --from=builder /app/build/libs/*.jar app.jar
USER appuser
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
settings.gradle or
settings.gradle.kts file, remove that file from the COPY instruction. The example
assumes the Gradle wrapper and its wrapper files are committed to the project.
Let's understand why this Dockerfile has two stages.
- Builder stage: Uses a JDK and Gradle wrapper to compile and package the application.
- Runtime stage: Uses a JRE image and copies only the executable JAR from the builder.
- USER: Runs the application as a non-root user.
- ENTRYPOINT: Starts the Spring Boot application.
Multi-stage builds separate build-time tools from runtime dependencies, which can reduce the final image size and attack surface.
Step 10: Create .dockerignore
Create a file named .dockerignore:
.git
.gradle
build
.idea
.vscode
*.iml
*.log
.env
.env.*
This prevents unnecessary files and local configuration from entering the Docker build context. Review your ignore rules so that required source files and Gradle wrapper files are not accidentally excluded.
Never copy secrets into an image. Build secrets and runtime secrets should be handled using suitable secret-management mechanisms.
Step 11: Create compose.yaml
Now comes the most useful part. We will run the Spring Boot application and MySQL together.
services:
app:
build:
context: .
dockerfile: Dockerfile
container_name: product-api
ports:
- "8081:8080"
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://db:3306/product_db
SPRING_DATASOURCE_USERNAME: product_user
SPRING_DATASOURCE_PASSWORD: ${DB_PASSWORD:?Set DB_PASSWORD}
depends_on:
db:
condition: service_healthy
restart: unless-stopped
db:
image: mysql:8.4
container_name: product-mysql
environment:
MYSQL_DATABASE: product_db
MYSQL_USER: product_user
MYSQL_PASSWORD: ${DB_PASSWORD:?Set DB_PASSWORD}
MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD:?Set DB_ROOT_PASSWORD}
volumes:
- mysql_data:/var/lib/mysql
healthcheck:
test: ["CMD-SHELL", "mysqladmin ping -h localhost -u root -p\"$$MYSQL_ROOT_PASSWORD\""]
interval: 10s
timeout: 5s
retries: 10
start_period: 30s
restart: unless-stopped
volumes:
mysql_data:
Notice that the application connects to db, not localhost. In Compose,
services on the default network can discover each other by service name.
The database port is not published to the host in this example. The Spring Boot service can reach it internally through the Compose network. If you need a local database client, you can add a port mapping for development.
Step 12: Configure Environment Variables
Create a local .env file next to compose.yaml:
DB_PASSWORD=local_product_password
DB_ROOT_PASSWORD=local_root_password
These are only sample local-development values. Do not commit this file to Git. The
.dockerignore file also excludes it from the image build context, but that does not
replace source-control ignore rules.
In production, use a suitable secret manager or deployment platform secret mechanism instead of
relying on a committed or casually shared .env file.
Step 13: Start the Application
Run the following command from the project root:
docker compose up --build -d
Docker Compose will:
- Build the Spring Boot image.
- Pull the MySQL image if it is not already available.
- Create the required network and volume.
- Start the MySQL container.
- Wait for the MySQL health check to report healthy.
- Start the Spring Boot container.
Step 14: Check Running Containers
docker compose ps
Check the application logs:
docker compose logs -f app
Check MySQL logs:
docker compose logs -f db
Step 15: Test the API Using Postman
Our Spring Boot application is exposed on host port 8081.
Create Product
Method: POST
URL: http://localhost:8081/api/products
Body:
{
"name": "Laptop",
"price": 65000.00
}
Get All Products
Method: GET
URL: http://localhost:8081/api/products
Get Product By ID
Method: GET
URL: http://localhost:8081/api/products/1
Delete Product
Method: DELETE
URL: http://localhost:8081/api/products/1
Step 16: Verify Data Persistence
Stop and remove the containers:
docker compose down
Start them again:
docker compose up -d
The MySQL named volume remains in place, so the database data should still be available. To remove the volume too, you would need:
docker compose down -v
Docker Compose vs Docker Run
| Docker Run | Docker Compose |
|---|---|
| Starts individual containers | Defines multi-container applications |
| Options passed through command line | Configuration stored in YAML |
| Useful for quick tests | Useful for repeatable environments |
| Manual setup of several services | Services and dependencies declared together |
| Commands can become long | Easy to share and maintain configuration |
Multi-Stage Docker Builds Explained
One of the most useful techniques for Java developers is a multi-stage build.
Consider a traditional Java build. It may require:
- JDK
- Gradle or Maven
- Source code
- Build plugins
- Application dependencies
But after building the application, the runtime generally needs only the executable JAR and a compatible Java runtime. Why include the entire build environment in the final image if it is not needed to run the application? Multi-stage builds solve this by separating the builder and runtime stages.
Only the JAR crosses from the builder stage into the runtime stage.
Benefits include:
- Smaller final images in many applications.
- Fewer build tools in the runtime image.
- Reduced attack surface.
- Clear separation between building and running software.
- More efficient image distribution and deployment.
Multi-stage builds are recommended for production-oriented Dockerfiles. The final image size depends on the selected base image, dependencies, and application packaging.
Docker Security Best Practices
Docker makes application packaging easier, but container security still needs attention. A container is not automatically secure simply because it runs in isolation.
1. Do Not Run as Root Without a Reason
Create and use a dedicated non-root user in the runtime image whenever possible.
RUN useradd --system --uid 10001 appuser
USER appuser
2. Use Trusted Base Images
Prefer maintained official or verified images. Understand the support lifecycle of the chosen runtime and operating-system base image.
3. Avoid the Latest Tag for Controlled Deployments
Using latest can make builds less predictable because it may refer to different image
contents over time. Choose an intentional version and consider digest pinning for stricter
reproducibility.
4. Do Not Store Secrets in Dockerfiles
Never hardcode database passwords, API keys, or private tokens into Dockerfiles or source code. Use appropriate secret-management mechanisms.
5. Use .dockerignore
Exclude unnecessary files, local credentials, build output, and version-control metadata from the build context.
6. Scan Images for Vulnerabilities
Use image-scanning tools such as Docker Scout or other security scanners to identify vulnerable packages and outdated base images.
7. Keep Images Small and Focused
Use multi-stage builds and avoid adding unnecessary packages to runtime images.
8. Limit Container Privileges
Avoid privileged containers unless absolutely required. Apply suitable capabilities, resource limits, and security settings for your environment.
9. Do Not Publish Internal Ports Unnecessarily
Only expose the ports that need to be accessed from outside the Docker network.
10. Keep Docker and Base Images Updated
Regularly update the Docker platform, base images, operating-system packages, and application dependencies.
Common Docker Errors and How to Fix Them
Error 1: Port Is Already Allocated
Example:
Bind for 0.0.0.0:8080 failed:
port is already allocated
Reason: Another application or container is already using the host port.
Solution: Check running containers and change the host port if necessary.
docker ps
docker run -d -p 8081:80 nginx:alpine
Error 2: Container Exits Immediately
Reason: The main process may have completed or failed.
Solution:
docker ps -a
docker logs container-name
Check the application logs and entrypoint command.
Error 3: Cannot Connect to MySQL
Reason: The application may be using the wrong database hostname, port, credentials, or startup assumptions.
Solution:
- Use the Compose service name as the hostname.
- Verify that both containers share a network.
- Check MySQL logs.
- Use a health check and suitable application retry strategy.
- Verify the username, password, and database name.
Error 4: Image Not Found
Reason: The image name or tag may be incorrect, or the registry may not contain it.
Solution:
docker pull nginx:alpine
docker images
Error 5: No Space Left on Device
Reason: Docker images, containers, build cache, or volumes may consume available disk space.
Solution:
docker system df
docker image prune
docker builder prune
Review resources before deleting them. Do not remove volumes containing important data.
Error 6: Docker Daemon Is Not Running
Reason: Docker Desktop or the Docker Engine may not be running.
Solution: Start Docker Desktop and verify the engine status.
docker info
Error 7: Application Cannot Find a File Inside the Image
Reason: The file may not be inside the build context, may be excluded by
.dockerignore, or may be copied to a different path.
Solution: Verify the Dockerfile COPY paths and inspect the resulting image filesystem.
Docker vs Kubernetes
Docker and Kubernetes are often mentioned together, but they solve different problems. Docker provides tools and technologies for building and running containers. Kubernetes is a container orchestration platform that manages containerized workloads across a cluster.
| Docker | Kubernetes |
|---|---|
| Builds and runs containers | Orchestrates containerized workloads |
| Creates images using Dockerfiles | Deploys workloads using Kubernetes resources |
| Docker Compose manages local multi-container applications | Manages workloads across a cluster |
| Useful for development and container workflows | Useful for large-scale orchestration |
| Provides Docker Engine and related tools | Uses a container runtime through the CRI |
Docker is not a requirement for every Kubernetes cluster. Kubernetes supports compatible container runtimes through the Container Runtime Interface.
Frequently Asked Interview Questions
1. What is Docker?
Docker is a platform and ecosystem for building, distributing, and running applications in containers.
2. What is a Docker image?
An image is a read-only template containing the filesystem and configuration needed to create a container.
3. What is a Docker container?
A container is an instance created from an image. It runs an application in an isolated environment.
4. What is the difference between an image and a container?
An image is the template, while a container is the running or stopped instance created from that template.
5. What is a Dockerfile?
A Dockerfile is a text file containing instructions used to build a Docker image.
6. What is the difference between RUN and CMD?
RUN executes commands during image building. CMD defines the default command executed when a container starts.
7. What is the difference between CMD and ENTRYPOINT?
CMD provides a default command or arguments that can be overridden. ENTRYPOINT defines the main executable. They can also be combined to provide default arguments.
8. What is Docker Compose?
Docker Compose defines and runs multi-container applications using a YAML configuration file.
9. What is a Docker volume?
A volume is Docker-managed persistent storage that can be used independently of a container's lifecycle.
10. What is a bind mount?
A bind mount connects a specific host filesystem path to a path inside a container.
11. What is Docker networking?
Docker networking allows containers to communicate with one another and with external systems.
12. What is a multi-stage build?
It uses multiple build stages so that build-time dependencies can be excluded from the final runtime image.
13. What is the difference between EXPOSE and -p?
EXPOSE documents the container port. The -p option publishes a container port on the
host.
14. Why should we use .dockerignore?
It excludes unnecessary files from the build context, helping reduce build time and preventing accidental inclusion of local files or secrets.
15. How does a Spring Boot container connect to MySQL in Docker Compose?
Both services share a Compose network. The Spring Boot application uses the MySQL service name as
the database hostname, for example jdbc:mysql://db:3306/product_db.
16. What happens to container data after removing a container?
Data stored only in the container's writable layer is removed with the container. Data stored in a persistent volume can remain available.
17. What is Docker Hub?
Docker Hub is a registry service where developers can find, store, and distribute container images.
18. How can you check container logs?
Use docker logs container-name or docker compose logs service-name.
19. Why should we avoid running containers as root?
Running as a non-root user reduces the impact of some security issues if an application or container is compromised.
20. Is Docker a replacement for Kubernetes?
No. Docker and Kubernetes have different roles. Docker provides container build and runtime tooling, while Kubernetes orchestrates containerized workloads across clusters.
Practical Docker Assignments
Try these exercises to strengthen your Docker knowledge:
- Install Docker Desktop and run the
hello-worldcontainer. - Run an Nginx container and access it through a browser.
- Create your own Dockerfile for a simple Java application.
- Build an image and run multiple containers from the same image.
- Run MySQL using a named volume and verify data persistence.
- Create a custom Docker network and connect two containers.
- Containerize a Spring Boot REST API.
- Use Docker Compose to run Spring Boot and MySQL together.
- Convert a single-stage Java Dockerfile into a multi-stage build.
- Run a Spring Boot application with MySQL and Redis using Compose.
- Inspect container logs and troubleshoot a failed application.
- Build, tag, and push an image to a private or public registry.
Useful Docker Commands Cheat Sheet
| Command | Purpose |
|---|---|
docker --version | Check Docker version |
docker pull image | Download an image |
docker images | List images |
docker build -t name . | Build an image |
docker run image | Run a container |
docker ps | List running containers |
docker ps -a | List all containers |
docker logs name | View container logs |
docker exec -it name sh | Open a shell in a container |
docker stop name | Stop a container |
docker start name | Start a container |
docker rm name | Remove a container |
docker rmi image | Remove an image |
docker volume ls | List volumes |
docker network ls | List networks |
docker stats | View resource usage |
docker compose up -d | Start Compose services |
docker compose down | Stop and remove Compose containers and networks |
docker compose logs -f | Follow Compose logs |
docker system df | Check Docker disk usage |
Your Docker Checklist
Before containerizing an application, ask:
- Do I need a container at all? For a single, simple script, running it directly may be enough.
- Is the base image trusted and maintained? Prefer official or verified images with a supported lifecycle.
- Am I running as a non-root user? Add a dedicated user in the runtime image.
- Have I pinned image versions? Avoid
latestfor controlled deployments. - Do I need persistent data? Use a named volume for databases and stateful services.
- Are secrets outside the image? Use environment variables, secret managers, or platform secret mechanisms.
- Have I written a health check? Especially for databases and dependent services.
- Is the image multi-stage? Keep build tools out of the final runtime image.
- Have I scanned the image for vulnerabilities? Use Docker Scout or another scanner.
- Is the app ready for graceful shutdown? Handle termination signals and in-flight requests.
Start small. Containerize one Spring Boot API first. Once the workflow is stable, add MySQL, then Redis, then a CI/CD pipeline.
Best Practices for Experienced Java Developers
- Use a multi-stage Dockerfile: Build with a JDK image, run with a JRE image.
- Leverage layer caching: Copy dependency files before source files to avoid unnecessary rebuilds.
- Keep the runtime image minimal: Use JRE or distroless images when possible.
- Enable Spring Boot graceful shutdown: Set
server.shutdown=gracefuland configure a shutdown timeout. - Externalize configuration: Use environment variables and Spring profiles rather than baking config into the image.
- Add health checks: Expose Spring Boot Actuator endpoints for readiness and liveness.
- Set memory limits: Use
-XX:MaxRAMPercentageso the JVM respects container limits. - Pin base image digests: For reproducible builds in regulated environments.
- Scan images in CI: Fail builds on critical vulnerabilities where possible.
- Do not overengineer: If a simple deployment already works cleanly, extra tooling may add unnecessary complexity.
Final Thoughts
Docker is an important tool for modern Java and backend developers. It makes application packaging, local development, testing, and deployment workflows more consistent. If you are a fresher, start by learning images, containers, Dockerfiles, and the most common commands. Then move towards volumes, networking, and Docker Compose.
If you are an experienced Spring Boot developer, focus on multi-stage builds, image optimization, non-root containers, secrets management, health checks, observability, and deployment automation.
The most effective way to learn Docker is to containerize a real application. Start with a simple Spring Boot API, connect it to MySQL, add Redis, and gradually move towards a complete microservices environment. Do not just memorize Docker commands. Understand what happens when an image is built, a container starts, a service connects to another service, and data is persisted.
Keep learning, keep building, and keep shipping better applications!
Related topics: Spring Boot Docker Tutorial, Docker Compose for Java Developers, Spring Boot Actuator Health Checks, Multi-Stage Docker Builds for Java, MySQL in Docker for Local Development, Docker Security Best Practices, Docker vs Kubernetes, Spring Boot Microservices with Docker
Practice task: Extend the Spring Boot + MySQL project in this tutorial by adding a
Redis cache container. Configure Spring Boot to use Redis for caching product lookups, then verify
that the application still works after a docker compose down and
docker compose up -d cycle. Think about which data should persist and which data can be
rebuilt on startup.
Found this Docker tutorial useful? Share it with your Java developer friends and colleagues who are learning Docker, Spring Boot, and microservices. Follow for more practical tutorials on Java, Spring Boot, Docker, Redis, Microservices, System Design, and backend development.
Note: This tutorial is intended for learning and local development. Production deployments require environment-specific security controls, secrets management, backups, monitoring, resource limits, image scanning, access control, and a suitable deployment platform.
No comments:
Post a Comment