Docker for Beginners: A Hands-On Tutorial to Master Containers from Scratch

3.49K 0 0 0 0

✅ Chapter 2: Working with Docker Images and Containers

🚀 Overview

After setting up Docker and understanding its basic architecture in Chapter 1, it's time to dive into its two most essential building blocks: Docker Images and Docker Containers.

  • A Docker image is a snapshot or template of an application with all its dependencies.
  • A Docker container is a running instance of that image.

This chapter focuses on how to create, manage, inspect, and optimize images and containers to power real-world application workflows.


🧱 What is a Docker Image?

A Docker image is a layered, read-only template used to create containers. It includes:

  • Application code
  • Runtime (e.g., Python, Node.js)
  • Libraries and dependencies
  • Environment variables
  • Configuration files
  • Entry commands

Images are immutable once built. Any changes made at runtime are saved as a new layer on top of the existing image.


🔍 Docker Image Lifecycle

text

 

Dockerfile → Build → Image → Run → Container → Modify (Optional) → Commit → New Image


🛠️ Dockerfile Basics

To build a Docker image, you write a Dockerfile. Let’s break down a sample.

Dockerfile

 

# Use official Python image

FROM python:3.10

 

# Set working directory

WORKDIR /usr/src/app

 

# Copy files into container

COPY requirements.txt .

RUN pip install -r requirements.txt

COPY . .

 

# Default command

CMD [ "python", "./app.py" ]

🧾 Common Dockerfile Instructions

Instruction

Description

FROM

Base image to build upon

WORKDIR

Set working directory inside container

COPY

Copy files from host to container

RUN

Execute command during image build

CMD

Default command to run when container starts


🧪 Build Your First Image

bash

 

docker build -t my-python-app .

  • -t assigns a name (tag) to the image.
  • . means build context is the current directory.

📦 Docker Container: What Is It?

A container is a runtime instance of an image. It runs in isolation with its own file system, networking, and process space—but shares the host’s kernel.

Containers are ephemeral by default. Once stopped or deleted, their internal state is lost (unless volumes are used).


🔄 Lifecycle of a Docker Container

Stage

Command Example

Create

docker create <image>

Start

docker start <container>

Run

docker run <image>

Stop

docker stop <container>

Remove

docker rm <container>

Inspect

docker inspect <container>


🔧 Working with Docker Images

Listing Images

bash

 

docker images

Removing Unused Images

bash

 

docker rmi <image-id>

To remove all dangling (unused) images:

bash

 

docker image prune


🧰 Working with Docker Containers

Create and Start

bash

 

docker run -d --name my-container nginx

Flag

Purpose

-d

Detached mode (runs in background)

--name

Assign a custom name

View Running Containers

bash

 

docker ps

To include stopped containers:

bash

 

docker ps -a

Stop and Remove

bash

 

docker stop my-container

docker rm my-container


🔍 Inspecting Images and Containers

Inspect metadata:

bash

 

docker inspect my-container

Check logs:

bash

 

docker logs my-container

Enter a running container:

bash

 

docker exec -it my-container bash

Helpful for debugging, running commands, or exploring runtime behavior.


🧱 Container vs Image: A Quick Reference

Feature

Docker Image

Docker Container

Type

Blueprint (static)

Runtime instance (dynamic)

Modifiable

No (requires rebuild)

Yes (but changes don’t persist)

Stored

Locally or on Docker Hub

In memory, deleted if removed

Usage

Used to launch containers

Executes the application

Example Command

docker build -t myapp .

docker run myapp


📁 Exporting and Importing Images

Save image to .tar:

bash

 

docker save -o myapp.tar my-python-app

Load saved image:

bash

 

docker load -i myapp.tar


🧹 Cleaning Up Docker

Clean up all stopped containers, unused images, networks:

bash

 

docker system prune

To remove everything including volumes:

bash

 

docker system prune -a --volumes

Use with caution!


💡 Advanced Tip: Tagging Images

Docker supports image versioning using tags.

bash

 

docker build -t myapp:1.0 .

docker build -t myapp:latest .

Then you can run specific versions:

bash

 

docker run myapp:1.0

This is critical for managing production vs development versions.


🗂️ Docker Image Layer Caching

Each instruction in a Dockerfile creates a layer. Docker caches these to speed up builds.

Dockerfile

 

# Efficient layering

COPY requirements.txt .

RUN pip install -r requirements.txt

 

COPY . .

If requirements.txt doesn’t change, Docker will cache the pip install step.


🧰 Debugging Common Errors

Error

Fix

Cannot connect to Docker daemon

Make sure Docker is running and you have permission

Image not found

Check Docker Hub spelling or use docker pull first

Permission denied

Use sudo or add your user to the docker group

Ports already in use

Change exposed host port using -p 8081:80


🔗 Docker Hub: Managing Public and Private Images

Login:

bash

 

docker login

Push an image:

bash

 

docker tag myapp username/myapp

docker push username/myapp

Pull an image:

bash

 

docker pull nginx

Use docker search <keyword> to find images.


🧠 Summary of Chapter 2

You’ve now explored:

  • How to build Docker images using Dockerfiles
  • How to run, stop, inspect, and remove containers
  • The difference between images and containers
  • Container lifecycle and runtime customization
  • Tagging and optimizing images for caching
  • Exporting, importing, and debugging containers


In the next chapter, we’ll explore networking and persistent storage with Docker.

Back

FAQs


✅ 1. What is Docker and why should I use it?

Answer: Docker is a containerization platform that allows developers to package applications and their dependencies into isolated units called containers. It ensures consistency across different environments, speeds up deployment, and makes application scaling easier.

✅ 2. What is the difference between a Docker container and a virtual machine (VM)?

Answer: Containers share the host system’s OS kernel, making them lightweight and fast, while VMs run a full guest OS, making them heavier and slower. Containers are ideal for microservices and rapid deployment, whereas VMs are better suited for full OS-level isolation.

✅ 3. Do I need to know Linux to use Docker?

Answer: While basic knowledge of Linux command-line tools is helpful, it’s not mandatory to start with Docker. Docker also works on Windows and macOS, and many beginner tutorials (including this one) walk you through all required commands step-by-step.

✅ 4. What is the difference between a Docker image and a Docker container?

Answer: A Docker image is a read-only template used to create containers, while a Docker container is a running instance of an image. You can think of an image as a blueprint and a container as the building made from it.

✅ 5. How do I install Docker on my computer?

Answer: You can download Docker Desktop for Windows or macOS from https://www.docker.com, or install Docker Engine on Linux using your distro’s package manager (like apt, yum, or dnf).

✅ 6. What is a Dockerfile and how is it used?

Answer: A Dockerfile is a script that contains a set of instructions for building a Docker image. It typically includes a base image, environment setup, file copying, and the command to run when the container starts.

✅ 7. What is Docker Hub and is it free?

Answer: Docker Hub is a cloud-based repository where users can share and store Docker images. It has free tiers and allows you to download popular open-source images or push your own images to share with others or use in CI/CD pipelines.

✅ 8. Can I run multiple containers at the same time?

Answer: Yes, you can run multiple containers simultaneously. Tools like Docker Compose even allow you to define and manage multi-container applications using a simple YAML configuration file.

✅ 9. How do I persist data in a Docker container?

Answer: You can use volumes or bind mounts to persist data outside the container’s lifecycle. This allows your application data to survive container restarts or recreations.

✅ 10. Is Docker secure?

Answer: Docker offers many security benefits like container isolation and image scanning. However, security also depends on your image sources, proper configurations, and updates. It's important to follow Docker security best practices for production deployments.