How to Create Docker Containers on Linux

DockerDockerBeginner
Practice Now

Introduction

This comprehensive Docker tutorial provides developers and system administrators with a practical guide to understanding and implementing containerization technology. By exploring Docker's core concepts, installation procedures, and fundamental commands, learners will gain essential skills for creating lightweight, portable application environments.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL docker(("`Docker`")) -.-> docker/ContainerOperationsGroup(["`Container Operations`"]) docker(("`Docker`")) -.-> docker/ImageOperationsGroup(["`Image Operations`"]) docker(("`Docker`")) -.-> docker/DockerfileGroup(["`Dockerfile`"]) docker/ContainerOperationsGroup -.-> docker/create("`Create Container`") docker/ContainerOperationsGroup -.-> docker/ps("`List Running Containers`") docker/ContainerOperationsGroup -.-> docker/run("`Run a Container`") docker/ContainerOperationsGroup -.-> docker/start("`Start Container`") docker/ContainerOperationsGroup -.-> docker/stop("`Stop Container`") docker/ImageOperationsGroup -.-> docker/pull("`Pull Image from Repository`") docker/ImageOperationsGroup -.-> docker/images("`List Images`") docker/DockerfileGroup -.-> docker/build("`Build Image from Dockerfile`") docker/ContainerOperationsGroup -.-> docker/ls("`List Containers`") subgraph Lab Skills docker/create -.-> lab-392827{{"`How to Create Docker Containers on Linux`"}} docker/ps -.-> lab-392827{{"`How to Create Docker Containers on Linux`"}} docker/run -.-> lab-392827{{"`How to Create Docker Containers on Linux`"}} docker/start -.-> lab-392827{{"`How to Create Docker Containers on Linux`"}} docker/stop -.-> lab-392827{{"`How to Create Docker Containers on Linux`"}} docker/pull -.-> lab-392827{{"`How to Create Docker Containers on Linux`"}} docker/images -.-> lab-392827{{"`How to Create Docker Containers on Linux`"}} docker/build -.-> lab-392827{{"`How to Create Docker Containers on Linux`"}} docker/ls -.-> lab-392827{{"`How to Create Docker Containers on Linux`"}} end

Docker Fundamentals

Introduction to Containerization Technology

Docker is a powerful containerization platform that revolutionizes software development and deployment. It enables developers to package applications with all their dependencies into standardized units called containers, ensuring consistent performance across different computing environments.

Core Concepts of Docker

What is Docker?

Docker is an open-source platform for containerization technology that allows developers to automate application deployment, scaling, and management. Unlike traditional virtual machines, Docker containers share the host system's kernel, making them lightweight and efficient.

graph TD A[Application Code] --> B[Docker Container] B --> C[Consistent Deployment] B --> D[Isolated Environment]

Key Docker Components

Component Description Purpose
Docker Engine Core runtime Builds and runs containers
Docker Image Read-only template Defines container configuration
Docker Container Runnable instance Executes application

Installation on Ubuntu 22.04

## Update package index
sudo apt update

## Install dependencies
sudo apt install apt-transport-https ca-certificates curl software-properties-common

## Add Docker's official GPG key
curl -fsSL  | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

## Set up stable repository
echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg]  $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

## Install Docker Engine
sudo apt update
sudo apt install docker-ce docker-ce-cli containerd.io

Basic Docker Commands

## Check Docker version
docker --version

## Pull an image
docker pull ubuntu:latest

## List images
docker images

## Run a container
docker run -it ubuntu:latest /bin/bash

Use Cases for Docker Containerization

Docker is widely used in:

  • Microservices architecture
  • Continuous Integration/Continuous Deployment (CI/CD)
  • Cloud-native application development
  • Consistent development and production environments

Building Docker Images

Understanding Docker Images

Docker images are read-only templates that contain everything needed to run an application: code, runtime, libraries, environment variables, and configuration files. They serve as blueprints for creating containers.

graph LR A[Dockerfile] --> B[Docker Image] B --> C[Docker Container]

Dockerfile Basics

A Dockerfile is a text document containing instructions for building a Docker image. Each instruction creates a new layer in the image.

Dockerfile Instruction Types

Instruction Purpose Example
FROM Set base image FROM ubuntu:22.04
RUN Execute commands RUN apt-get update
COPY Copy files COPY app.py /app/
WORKDIR Set working directory WORKDIR /app
CMD Default command CMD ["python", "app.py"]

Creating a Sample Python Application Image

Sample Project Structure

/project
├── Dockerfile
└── app.py

app.py

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello, Docker World!"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

Dockerfile

## Use official Python runtime as base image
FROM python:3.9-slim

## Set working directory
WORKDIR /app

## Copy project files
COPY app.py requirements.txt ./

## Install dependencies
RUN pip install --no-cache-dir -r requirements.txt

## Expose port
EXPOSE 5000

## Define default command
CMD ["python", "app.py"]

Building and Managing Docker Images

## Create requirements.txt
echo "flask" > requirements.txt

## Build Docker image
docker build -t my-flask-app .

## List images
docker images

## Run container from image
docker run -p 5000:5000 my-flask-app

Image Optimization Strategies

  • Use multi-stage builds
  • Minimize layer count
  • Leverage build cache
  • Use specific image tags
  • Remove unnecessary files

Container Management

Container Lifecycle Overview

Docker containers have a complex lifecycle with multiple states, from creation to termination. Understanding these states is crucial for effective container management and orchestration.

stateDiagram-v2 [*] --> Created Created --> Running Running --> Paused Paused --> Running Running --> Stopped Stopped --> Removed Removed --> [*]

Essential Docker Container Commands

Command Function Example
docker create Create container docker create nginx
docker start Start container docker start container_id
docker stop Stop running container docker stop container_id
docker restart Restart container docker restart container_id
docker rm Remove container docker rm container_id

Container Inspection and Monitoring

## List running containers
docker ps

## List all containers
docker ps -a

## Inspect container details
docker inspect container_id

## View container logs
docker logs container_id

## Monitor container resource usage
docker stats

Container Resource Management

## Run container with CPU and memory limits
docker run -d \
    --cpus="1.5" \
    --memory="512m" \
    --name limited-container \
    nginx

Advanced Container Networking

## Create custom network
docker network create mynetwork

## Run container in specific network
docker run -d \
    --network=mynetwork \
    --name web-container \
    nginx

Container Scaling Strategies

## Scale multiple container instances
docker-compose up -d --scale web=3

Persistent Data Management

## Create volume
docker volume create myvolume

## Mount volume to container
docker run -v myvolume:/app/data \
    --name data-container \
    ubuntu

Best Practices

  • Use lightweight base images
  • Implement health checks
  • Minimize container size
  • Use multi-stage builds
  • Implement proper logging
  • Secure container configurations

Summary

Docker represents a revolutionary approach to software deployment, offering developers a powerful platform for creating consistent, isolated, and scalable application containers. By mastering Docker's fundamental techniques, professionals can streamline development workflows, enhance system efficiency, and simplify complex application management across diverse computing infrastructures.

Other Docker Tutorials you may like