DevOps

Docker for Beginners: A Practical Guide to Containers, Images, and Deployment

Have you ever built an application that worked perfectly on your computer but failed when you tried to run it on another machine? Maybe the other computer had…

D
DevByteTechnical Author
Published
18 min read4 views
Docker for Beginners: A Practical Guide to Containers, Images, and Deployment

Have you ever built an application that worked perfectly on your computer but failed when you tried to run it on another machine? Maybe the other computer had a different Node.js version, a missing Python package, or a different system configuration.

This is a common problem in software development. Developers need a reliable way to package applications with their dependencies so they can run consistently across different environments.

Docker helps solve this problem by packaging an application and its required dependencies into a container.

Docker is widely used in backend development, DevOps, cloud computing, and application deployment. If you work with Node.js, Python, React, Next.js, databases, or APIs, learning Docker can make your development workflow much easier.

In this beginner-friendly guide, you will learn what Docker is, how containers work, how to install Docker, and how to run your first container. You will also build a simple Node.js application, create a Docker image, use Docker Compose, and learn how to manage containers in real projects.

No previous Docker experience is required.

1. What Is Docker?

Docker is a platform that helps developers build, package, distribute, and run applications using containers.

A container packages an application with the files, libraries, and configuration it needs to run. It uses the host operating system's kernel rather than running a complete guest operating system like a traditional virtual machine.

Imagine you develop a Node.js application on your laptop. It requires a particular Node.js version and several npm packages.

Without Docker, another developer might need to install the correct Node.js version, install the packages, configure the environment, and troubleshoot differences between machines.

With Docker, you can define the application's environment and build an image that can be run on another compatible machine with Docker installed.

For example, you can start a container using:

docker run hello-world

Docker downloads the image if it is not already available locally, creates a container, and runs the program inside it.

This makes Docker useful for development, testing, and deployment.

Why Do Developers Use Docker?

Docker helps developers:

  • Run applications in consistent environments.

  • Avoid many dependency and configuration conflicts.

  • Start databases and supporting services quickly.

  • Package applications for deployment.

  • Create repeatable development and testing environments.

  • Run multiple isolated application containers on one machine.

  • Simplify collaboration between developers.

Docker does not eliminate every environment-related problem, but it makes many of them easier to manage.

2. What Problem Does Docker Solve?

Consider a simple example.

You build a Node.js application using Node.js 22. It works on your laptop, but another developer has an older Node.js version. The application might fail because of incompatible runtime features or dependencies.

A similar issue can occur when moving an application from development to a production server.

Docker lets you define the environment your application expects.

<box border radius="xl" padding={4} gap={3}> <title size="md">Without Docker</title> <box background="surface-secondary" radius="lg" padding={3} gap={1}> <text weight="medium">Developer's computer</text> <text color="secondary" size="sm">Node.js 22, package versions, local configuration</text> </box> <box align="center"> <icon name="arrow-down" size="lg" color="secondary" /> </box> <box background="surface-secondary" radius="lg" padding={3} gap={1}> <text weight="medium">Production server</text> <text color="secondary" size="sm">Different runtime or missing dependencies may cause errors</text> </box> <divider color="subtle" /> <title size="md">With Docker</title> <box border radius="lg" padding={3} gap={1}> <text weight="medium">Docker image</text> <text color="secondary" size="sm">Application code, required packages, and runtime environment</text> </box> <box align="center"> <icon name="arrow-down" size="lg" color="secondary" /> </box> <grid columns={2} gap={2}> <grid-item> <box background="surface" border radius="lg" padding={3} gap={1}> <icon name="laptop" size="lg" /> <text weight="medium">Development</text> <text color="secondary" size="xs">Runs the container</text> </box> </grid-item> <grid-item> <box background="surface" border radius="lg" padding={3} gap={1}> <icon name="server" size="lg" /> <text weight="medium">Production</text> <text color="secondary" size="xs">Runs the same image</text> </box> </grid-item> </grid> </box>

The key idea is that you can build an image once and run it in multiple compatible environments, while supplying environment-specific configuration separately.

3. What Is the Difference Between Docker and a Virtual Machine?

Beginners often confuse Docker containers with virtual machines (VMs). Both provide isolation, but they work differently.

<grid columns={2} gap={3}> <grid-item> <AsyncImage query="Docker container architecture diagram multiple containers shared host operating system kernel" aspectRatio="4:3" width="100%" /> Docker containers

<text color="secondary" size="sm">Share the host kernel and isolate applications and their environments. They are generally lightweight and start quickly.</text>

</grid-item> <grid-item> <AsyncImage query="virtual machine architecture hypervisor guest operating systems diagram" aspectRatio="4:3" width="100%" /> Virtual machines

<text color="secondary" size="sm">Run separate guest operating systems on virtualized hardware. They generally require more resources.</text>

</grid-item> </grid>

Here is a simple comparison:

Feature

Docker Container

Virtual Machine

Operating system

Shares the host kernel

Runs a guest OS

Resource usage

Usually lower

Usually higher

Startup time

Usually fast

Usually slower

Isolation

Process and resource isolation

Hardware-level virtualization boundary

Common use

Applications and services

Full OS environments and stronger OS separation

Containers are not a replacement for every virtual machine. Virtual machines are useful when you need different operating systems or a separate guest kernel.

On macOS and Windows, Docker Desktop generally runs Linux containers inside a lightweight Linux environment because the host operating system does not provide the Linux kernel directly.

4. Understand the Important Docker Terms

Before writing Docker commands, learn these five concepts.

Docker Image

A Docker image is a packaged, read-only template used to create containers.

It contains the application files, required dependencies, filesystem layers, and configuration needed to start the application.

For example:

docker pull nginx

This downloads the Nginx image from the configured container registry, usually Docker Hub.

Docker Container

A container is a running or stopped instance created from an image.

For example:

docker run nginx

Docker creates and starts a container from the Nginx image.

You can create multiple containers from the same image.

Dockerfile

A Dockerfile contains instructions for building a Docker image.

It tells Docker which base image to use, where to place application files, which dependencies to install, and how the application should start.

Docker Registry

A registry stores and distributes Docker images.

Docker Hub is a popular public registry, but private registries are also available.

Docker Volume

A volume stores data outside a container's writable filesystem so that data can persist when a container is replaced or removed.

Volumes are commonly used for databases and other stateful services.

How These Concepts Work Together

<box border radius="xl" padding={3} gap={2} align="center"> <box background="surface-secondary" radius="lg" padding={3} width="100%" align="center"> <icon name="file-text" size="xl" /> Dockerfile <text color="secondary" size="sm">Instructions for packaging an application</text> </box> <icon name="arrow-down" size="lg" color="secondary" /> <box background="surface" border radius="lg" padding={3} width="100%" align="center"> <icon name="package" size="xl" /> Docker Image <text color="secondary" size="sm">Built application template</text> </box> <icon name="arrow-down" size="lg" color="secondary" /> <box background="surface-secondary" radius="lg" padding={3} width="100%" align="center"> <icon name="container" size="xl" /> Docker Container <text color="secondary" size="sm">Running instance of the image</text> </box> <icon name="arrow-down" size="lg" color="secondary" /> <box background="surface" border radius="lg" padding={3} width="100%" align="center"> <icon name="globe" size="xl" /> Application <text color="secondary" size="sm">Serves requests or performs a task</text> </box> </box>

5. How to Install Docker

Docker Desktop is a convenient option for beginners using macOS or Windows. Linux users can install Docker Engine using the instructions for their distribution.

Install Docker on macOS

  1. Visit the official Docker Desktop download page.

  2. Download the version that matches your Mac's processor.

  3. Install Docker Desktop.

  4. Open Docker Desktop and wait until its engine is running.

  5. Open your terminal and verify the installation.

Run:

docker --version

Then check:

docker info

The first command displays the Docker client version. The second shows information about the Docker environment and requires the engine to be available.

If Docker is running correctly, you are ready to create your first container.

Install Docker on Windows or Linux

  • Windows: Follow the official Docker Desktop instructions and the applicable system requirements.

  • Linux: Follow the official Docker Engine installation guide for your distribution.

Official documentation: Install Docker

Avoid installing Docker from untrusted download sites.

6. Run Your First Docker Container

Let's run a simple container to verify that Docker works.

Open your terminal and execute:

docker run hello-world

If the image is not available locally, Docker pulls it from a registry. It then creates a container and runs the program.

You should see a message explaining that Docker is working correctly.

Now list all containers:

docker ps -a

This command displays running and stopped containers.

To list only running containers:

docker ps

The hello-world container normally exits after printing its message because it does not run a long-lived server.

7. Run a Web Server Using Docker

Now let's run a real web server.

Nginx is a popular web server and reverse proxy. We can run it without installing Nginx directly on our computer.

Execute:

docker run -d --name my-nginx -p 8080:80 nginx

Let's understand this command.

  • docker run creates and starts a container.

  • -d runs the container in the background.

  • --name my-nginx assigns a readable name to the container.

  • -p 8080:80 maps port 8080 on your computer to port 80 inside the container.

  • nginx specifies the image to run.

Open your browser and visit:

http://localhost:8080

You should see the default Nginx welcome page.

What Does Port Mapping Mean?

The Nginx server listens on port 80 inside its container. Your computer exposes it through port 8080.

The mapping follows this format:

HOST_PORT:CONTAINER_PORT

For example:

docker run -d -p 3000:3000 my-app

This maps port 3000 on the host to port 3000 in the container.

The application must also listen on the correct interface inside the container. For a web API, that often means binding to 0.0.0.0 rather than only 127.0.0.1.

8. Essential Docker Commands for Beginners

Here are the commands you will use regularly.

Command

Purpose

docker --version

Check the Docker CLI version

docker pull nginx

Download an image

docker images

List local images

docker ps

List running containers

docker ps -a

List all containers

docker run nginx

Create and run a container

docker stop my-nginx

Stop a running container

docker start my-nginx

Start an existing stopped container

docker restart my-nginx

Restart a container

docker logs my-nginx

View container logs

docker exec -it my-nginx sh

Open a shell if the image includes one

docker rm my-nginx

Remove a stopped container

docker rmi nginx

Remove a local image when unused

You can stop the Nginx container you created earlier:

docker stop my-nginx

Remove the stopped container:

docker rm my-nginx

Removing a container does not automatically remove its image or any separately stored volumes.

Be careful with cleanup commands that delete resources, especially on production systems.

9. Build Your First Dockerized Node.js Application

Now let's build a practical project.

We will create a simple Node.js API and run it inside Docker. This example is useful for developers who want to learn how Docker fits into backend development.

Step 1: Create a project

Create a folder:

mkdir docker-node-api
cd docker-node-api

Initialize a Node.js project:

npm init -y

Install Express:

npm install express

Step 2: Create server.js

Create a file named server.js:

const express = require("express");

const app = express();
const PORT = process.env.PORT || 3000;

app.get("/", (req, res) => {
  res.json({
    message: "Hello from Docker!",
    success: true,
  });
});

app.get("/health", (req, res) => {
  res.json({
    status: "ok",
  });
});

app.listen(PORT, "0.0.0.0", () => {
  console.log(`Server running on port ${PORT}`);
});

This creates two endpoints:

  • / returns a welcome message.

  • /health returns a basic health response.

Notice that the server listens on 0.0.0.0. This allows connections arriving through the container's network interface.

Step 3: Create a Dockerfile

Create a file named Dockerfile in the project root:

FROM node:22-alpine

WORKDIR /app

COPY package*.json ./

RUN npm ci --omit=dev

COPY server.js ./

EXPOSE 3000

CMD ["node", "server.js"]

Let's understand each instruction.

FROM node:22-alpine

Uses a Node.js base image. The Alpine variant is relatively small, although some native dependencies may require additional packages.

WORKDIR /app

Sets /app as the working directory inside the image.

COPY package*.json ./

Copies the package manifest and lockfile, if present, into the image.

RUN npm ci --omit=dev

Installs runtime dependencies using the lockfile. This command expects a package-lock.json, which npm install normally creates.

COPY server.js ./

Copies the application's server file into the image.

EXPOSE 3000

Documents that the application uses port 3000. It does not publish the port to your computer by itself.

CMD ["node", "server.js"]

Defines the default command used to start the application container.

Step 4: Create a .dockerignore file

Create .dockerignore in the same directory:

node_modules
.git
.env
npm-debug.log

This prevents unnecessary files from being sent into the Docker build context.

It is particularly important to exclude .env files and local dependencies that should not be copied into the image.

Step 5: Build the Docker image

Run:

docker build -t docker-node-api .

Here:

  • docker build builds an image.

  • -t docker-node-api assigns an image name.

  • . specifies the current directory as the build context.

Docker reads the Dockerfile and executes its build instructions.

Step 6: Run the container

Execute:

docker run -d \
  --name my-node-api \
  -p 3000:3000 \
  docker-node-api

Now open:

http://localhost:3000

You should receive a response similar to:

{
  "message": "Hello from Docker!",
  "success": true
}

You can also test the health endpoint:

http://localhost:3000/health

Step 7: Check the logs

If your application does not work, inspect the container logs:

docker logs my-node-api

To follow logs as they are produced:

docker logs -f my-node-api

To stop and remove the container:

docker stop my-node-api
docker rm my-node-api

Your built image remains available until you remove it.

10. What Is Docker Compose?

Docker Compose lets you define and manage an application containing multiple services using a YAML configuration file.

For example, a backend project might need:

  • A Node.js API.

  • A MongoDB database.

  • A Redis cache.

Without Compose, you would start each container separately and configure the networking and settings yourself.

With Compose, you define the services in one file and start them together.

Create a Docker Compose Project

For this example, use the Node.js API from the previous section and add MongoDB.

Create a file named compose.yaml:

services:
  api:
    build: .
    ports:
      - "3000:3000"
    environment:
      PORT: 3000
      MONGODB_URI: mongodb://mongo:27017/myapp
    depends_on:
      - mongo

  mongo:
    image: mongo:8
    volumes:
      - mongo_data:/data/db

volumes:
  mongo_data:

This defines two services:

  • api builds the Node.js application from the Dockerfile.

  • mongo runs MongoDB and stores its data in a named volume.

The example configures a database connection string, but the earlier API code does not yet connect to MongoDB. You would need to add a MongoDB driver or ODM and database connection logic before using the database.

Start the Services

Run:

docker compose up -d --build

Docker Compose builds the API image and starts the defined services.

Check their status:

docker compose ps

View logs:

docker compose logs -f

Stop the services:

docker compose down

The named mongo_data volume is preserved by default when you run docker compose down.

If you intentionally want to remove the named volumes too, use docker compose down -v. Be careful: that can delete your database data.

Important: depends_on controls service startup ordering, but it does not by itself guarantee that MongoDB is ready to accept connections. Production-quality setups should include health checks and appropriate application-level retry logic.

11. What Are Docker Volumes?

Containers have a writable filesystem, but data stored only inside a container can be lost when the container is removed.

Docker volumes provide persistent storage that exists independently of a particular container.

For example, MongoDB stores its database files under /data/db in the official image. Mounting a named volume at that location helps preserve data when you recreate the container.

Create a volume:

docker volume create my-data

Inspect it:

docker volume inspect my-data

List volumes:

docker volume ls

You can use a volume when starting a container:

docker run -d \
  --name mongo-db \
  -v my-data:/data/db \
  mongo:8

This example stores MongoDB's data in the named volume my-data.

Volumes are especially important for databases, uploaded files, and other data that must outlive a container.

For production databases, volumes are not a replacement for backups, replication, or a recovery plan.

12. What Is the Difference Between COPY and ADD?

Both COPY and ADD are Dockerfile instructions that place files into an image.

COPY copies files and directories from the build context into the image. ADD supports additional behavior, such as extracting local tar archives, and has other source-handling features.

For ordinary application files, prefer COPY because its behavior is simpler and easier to understand.

Example:

WORKDIR /app

COPY package.json ./
COPY server.js ./

Use ADD only when you specifically need its additional behavior and understand the implications.

Clear Dockerfiles are easier to review, troubleshoot, and maintain.

13. How Can You Reduce Docker Image Size?

Smaller images can reduce download times and storage use, although size should not be the only concern. Security, compatibility, and reliable builds matter too.

Useful techniques include:

  • Choose an appropriate base image.

  • Install only required production dependencies.

  • Use a .dockerignore file.

  • Avoid copying local node_modules into the image.

  • Use multi-stage builds for applications with build tools.

  • Remove unnecessary package-manager caches where appropriate.

  • Use trusted base images and keep them updated.

For example, the Node.js Dockerfile in this guide uses:

RUN npm ci --omit=dev

This installs the locked production dependencies without installing development dependencies.

For frontend applications, multi-stage builds can compile the application in one stage and copy only the necessary output into the final image.

Do not choose an image solely because it is the smallest. Very minimal images may require extra work to support native packages or troubleshoot runtime problems.

14. What Is the Difference Between RUN, CMD, and ENTRYPOINT?

These three Dockerfile instructions serve different purposes.

Instruction

Purpose

RUN

Executes a command while building the image

CMD

Defines the default command or arguments when a container starts

ENTRYPOINT

Defines the main executable for the container

Example:

FROM node:22-alpine

WORKDIR /app

COPY package*.json ./
RUN npm ci --omit=dev

COPY server.js ./

ENTRYPOINT ["node"]
CMD ["server.js"]

Here, RUN npm ci --omit=dev executes during the image build.

The ENTRYPOINT sets Node.js as the main executable, and CMD supplies the default script.

This distinction helps you understand how an image is built and how its container starts.

15. Common Docker Problems and How to Fix Them

Beginners often encounter these problems when they first start using Docker.

Problem 1: Port is already in use

You might see an error because another application is already using the host port.

Solution: choose a different host port.

docker run -d -p 8081:80 nginx

You can then visit http://localhost:8081.

Problem 2: Container exits immediately

Check the logs:

docker logs my-node-api

Common causes include application errors, missing dependencies, incorrect startup commands, or an application that completes its work and exits normally.

Problem 3: Changes are not reflected

If your application code changes, you may need to rebuild the image and recreate the container.

docker build -t docker-node-api .

Then recreate the container using the updated image.

During development, bind mounts and development-specific Compose configurations can help avoid rebuilding after every source change.

Problem 4: Container cannot connect to another service

When using Docker Compose, services can generally communicate using their service names on the Compose network.

For example, a backend connecting to the mongo service should use a hostname such as mongo, rather than localhost.

Inside a container, localhost refers to that container itself.

Problem 5: Database data disappears

Make sure database files are stored in a persistent volume or another suitable storage system rather than only in the container's writable layer.

Remember that deleting a named volume can permanently remove its data.

16. Docker Best Practices for Beginners

As you begin using Docker in real applications, follow these practices.

1. Use a .dockerignore file. Keep unnecessary files and secrets out of the build context.

2. Store configuration outside the image. Supply environment-specific settings at runtime.

3. Avoid hardcoding secrets. Use secure secret management rather than placing passwords or API keys directly in a Dockerfile.

4. Use trusted images. Select appropriate base images, pin versions or digests where reproducibility requires it, and update images regularly.

5. Run as a non-root user when practical. This reduces the potential impact of certain container compromises.

6. Keep images focused. Include only what is needed to build or run the application.

7. Monitor logs and health. Ensure you can identify failed containers and diagnose application errors.

8. Persist important data. Use volumes or external storage for state that must survive container replacement.

9. Understand networking. Know which ports are exposed, how services communicate, and which ports should remain private.

10. Test your deployment. A successful image build does not guarantee that the application works correctly at runtime.

17. What Should You Learn After Docker?

Once you understand images, containers, volumes, networks, and Compose, continue with these topics:

  1. Docker networking: Understand bridge networks, port mapping, and service discovery.

  2. Multi-stage builds: Create more efficient production images.

  3. Docker security: Learn non-root execution, image scanning, and secret management.

  4. Docker Compose: Manage APIs, databases, caches, and background workers together.

  5. CI/CD: Build, test, and publish images automatically.

  6. Cloud deployment: Learn how containers run on VPSs and cloud platforms.

  7. Kubernetes: Explore orchestration when your application needs more advanced deployment and scaling capabilities.

You do not need to learn Kubernetes immediately. First become comfortable building, running, debugging, and deploying a small Dockerized application.

Conclusion

Docker makes it easier to package applications and run them consistently across development, testing, and deployment environments.

In this guide, you learned the difference between images and containers, installed Docker, ran an Nginx container, created a Node.js API image, and explored Docker Compose and persistent volumes.

The best way to learn Docker is to practice. Start with a small API, containerize it, connect it to a database, and learn how to inspect logs and troubleshoot problems.

Once these basics feel comfortable, Docker will become a valuable tool in your backend development workflow.

Frequently Asked Questions

1. Is Docker difficult for beginners?

No. You can start with a few commands and gradually learn images, containers, volumes, and networks. Building and running a small application is a good first project.

2. Is Docker free to use?

Docker provides free and paid offerings, with terms depending on the product and type of use. Docker Engine is open source, while Docker Desktop has its own licensing terms. Check the official Docker website for current details.

3. Do I need to learn Linux before Docker?

No. Basic terminal commands and an understanding of files, processes, ports, and permissions are helpful, but you can learn the Linux concepts you need while learning Docker.

4. Can I use Docker with Node.js and Python?

Yes. Docker supports applications built with Node.js, Python, Java, Go, and many other technologies. Each application can use an appropriate base image and dependency setup.

5. Does Docker replace a VPS or cloud server?

No. Docker packages and runs applications, while a VPS or cloud server provides computing resources. You can install Docker on a VPS and use it to run your application containers.

6. Does Docker automatically make an application scalable?

No. Docker helps package and deploy applications consistently, but scaling requires additional decisions about application architecture, load balancing, databases, caching, and infrastructure.

7. What is the difference between Docker and Kubernetes?

Docker is commonly used to build and run containers. Kubernetes is a container orchestration platform that helps manage containerized applications across clusters, including scheduling, scaling, and recovery.

8. Should I use Docker for every project?

Not necessarily. Docker is valuable when consistent environments, dependency isolation, or repeatable deployment are important. For a small script or simple local project, using Docker may add unnecessary complexity.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘