How to Use Docker on Ubuntu: Complete Guide to Installation, Images, Dockerfile, and Optimization

目次

1. Introduction

What Is Docker?

Docker is a platform that uses container-based virtualization technology to efficiently develop, distribute, and run applications. Unlike traditional virtual machines (VMs), containers share the host OS kernel, allowing for faster startup and lower resource consumption.

Benefits of Using Docker on Ubuntu

Ubuntu is one of the Linux distributions with strong compatibility with Docker. The key reasons include:

  • Official Support: Docker officially supports Ubuntu, allowing easy installation through the official repository.
  • Stable Package Management: Ubuntu’s APT package manager makes version management straightforward.
  • Extensive Community Support: Ubuntu has a large global user base, making troubleshooting easier when issues arise.

What You Will Learn in This Article

This guide explains the following topics step by step:

  1. How to install Docker on Ubuntu
  2. Basic operations for Docker images
  3. Creating custom images using Dockerfile
  4. Setting up Japanese locale in an Ubuntu container
  5. Optimizing and minimizing Docker images
  6. Developing applications inside Ubuntu containers
  7. Common errors and troubleshooting

The content is useful for both beginners and advanced users, so feel free to reference it at any stage.

2. Installing Docker on Ubuntu

Installing Docker Using the Official Repository

In Ubuntu, you can easily install Docker using the official repository. Follow the steps below to set up your environment.

1. Remove Existing Docker Packages

Ubuntu may include a package called docker.io, which could be an older version. Remove it before installing the latest Docker.

sudo apt remove docker docker-engine docker.io containerd runc

2. Install Required Packages

Install dependency packages before installation.

sudo apt update
sudo apt install -y apt-transport-https ca-certificates curl software-properties-common

3. Add the Official Docker Repository

Add Docker’s official GPG key and configure the repository.

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

4. Install Docker

After adding the repository, install Docker.

sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io

5. Verify Installation

Check whether Docker is installed correctly by displaying the version information.

docker --version

Initial Setup After Installation

1. Start and Enable the Docker Service

Start the Docker service and enable automatic startup at boot.

sudo systemctl start docker
sudo systemctl enable docker

2. Allow Non-Root Users to Run Docker

By default, only root can run Docker. Allow regular users to execute Docker commands.

sudo usermod -aG docker $USER

Log out and log back in to apply the changes.

3. Test Docker Operation

Run the hello-world container using a regular user account.

docker run hello-world

If the output includes “Hello from Docker!”, the installation was successful.

3. Basic Operations of Docker Images

What Is a Docker Image?

A Docker image functions as a template for creating containers. By using an Ubuntu-based Docker image, you can quickly launch an Ubuntu environment.

Pulling Ubuntu Images from Docker Hub

Docker Hub provides numerous official Docker images. To download an Ubuntu image, run:

docker pull ubuntu

Starting and Stopping Containers

Use the downloaded Ubuntu image to start a container:

docker run -it ubuntu bash

This opens a shell inside the Ubuntu container, allowing you to operate within it.

List Containers

Display running containers:

docker ps

Display all containers, including stopped ones:

docker ps -a

Stopping and Removing Containers

Stop a running container:

docker stop [container ID or name]

Remove an unnecessary container:

docker rm [container ID or name]

Managing Docker Images

List downloaded Docker images:

docker images

Remove an image:

docker rmi [image ID]

4. Creating Custom Images with Dockerfile

What Is a Dockerfile?

A Dockerfile is a configuration file used to build Docker images. Based on the instructions written in the Dockerfile, you can create customized Docker images. This allows you to unify development environments or create images that include required packages.

Basic Syntax of Dockerfile

A Dockerfile typically includes the following commands:

CommandDescription
FROMSpecifies the base image
RUNExecutes commands to build the image
COPYCopies files into the container
WORKDIRSets the working directory
CMDDefault command executed when the container starts
ENTRYPOINTDefines the entry point of the container

Creating a Custom Ubuntu-Based Image

Follow the steps below to create a custom Ubuntu-based Docker image.

1. Create a Working Directory

First, create a new project directory and move into it.

mkdir my-ubuntu-image
cd my-ubuntu-image

2. Create a Dockerfile

Create a Dockerfile inside the directory and write the following content:

# Base Ubuntu official image
FROM ubuntu:latest

# Maintainer information (optional)
LABEL maintainer="your-email@example.com"

# Update package list and install basic tools
RUN apt update && apt install -y curl vim git

# Set working directory
WORKDIR /workspace

# Default command when the container starts
CMD ["bash"]

3. Build the Docker Image

Build a custom image from your Dockerfile:

docker build -t my-ubuntu-image .

The -t option assigns a name to the image.

4. Verify the Image

Check your newly built image:

docker images

5. Run a Container

Start a container from the custom image:

docker run -it my-ubuntu-image

This image includes tools such as curl and vim.

5. Setting Up a Japanese Environment in Ubuntu Containers

The default Ubuntu image uses an English environment. To use Japanese, additional configuration is required.

Setting Japanese Locale

To enable Japanese display and input in an Ubuntu container, install the Japanese locale.

1. Install Required Packages

apt update
apt install -y language-pack-ja locales

2. Configure the Locale

Generate and apply the locale:

locale-gen ja_JP.UTF-8
update-locale LANG=ja_JP.UTF-8

3. Apply the Settings

export LANG=ja_JP.UTF-8

Setting Up Japanese Input

To input Japanese characters in the terminal, install ibus-mozc:

apt install -y ibus-mozc

If using GUI applications, add the following environment variables:

export GTK_IM_MODULE=ibus
export XMODIFIERS=@im=ibus
export QT_IM_MODULE=ibus

Using GUI Applications

To run GUI applications inside a Docker container, use an X server on the host machine.

Run the container with X11 enabled:

docker run -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix my-ubuntu-image

6. Optimizing and Minimizing Docker Images

Docker images can be optimized to improve container startup speed and reduce storage usage. Here are several techniques for creating lightweight images.

How to Create a Lightweight Ubuntu-Based Image

The default ubuntu:latest image is relatively large. Using a more lightweight option like ubuntu:minimal helps reduce container size.

FROM ubuntu:minimal

Another option is to use Alpine Linux, which is significantly smaller than Ubuntu.

FROM alpine:latest
RUN apk add --no-cache bash curl

Using Alpine can reduce image size by several hundred megabytes.

Reducing Image Size by Removing Unnecessary Files

You can reduce image size by deleting unnecessary cache files created by apt-get.

RUN apt update && apt install -y curl vim \
    && apt clean \
    && rm -rf /var/lib/apt/lists/*

In particular, the rm -rf /var/lib/apt/lists/* command removes package lists and unused data.

Using Multi-Stage Builds

Multi-stage builds allow you to use tools only during the build process while keeping the final image lightweight.

FROM ubuntu as builder
RUN apt update && apt install -y gcc

FROM ubuntu:minimal
COPY --from=builder /usr/bin/gcc /usr/bin/gcc

This way, you avoid including development tools in the final image, resulting in a much smaller footprint.

7. Practical Example: Application Development in Ubuntu Containers

This section introduces how to set up development environments inside Ubuntu containers.

Setting Up a Python Development Environment

Create the following Dockerfile to set up a Python development environment in an Ubuntu container:

FROM ubuntu:latest
RUN apt update && apt install -y python3 python3-pip
CMD ["python3"]

Build the image and run the container:

docker build -t python-dev .
docker run -it python-dev

This environment allows you to use the python3 command for script development and testing.

Setting Up a Node.js Development Environment

To set up a Node.js development environment, use the following Dockerfile:

FROM ubuntu:latest
RUN apt update && apt install -y nodejs npm
CMD ["node"]

Build and run the container:

docker build -t node-dev .
docker run -it node-dev

This environment enables JavaScript execution and application development with the node command.

8. FAQ & Troubleshooting

Using Docker may lead to various issues. Below are common questions and typical solutions.

Difference Between Docker and Virtual Machines

  • Docker: Shares the host OS kernel, making it lightweight with fast container startup.
  • Virtual Machines (VMs): Each VM includes its own OS, resulting in higher resource usage and slower startup.

Docker excels in resource optimization and suits development environments and automated deployment.

Persisting Data in Ubuntu Containers

To retain data even after a container stops, use volume mounts:

docker run -v my_data:/data ubuntu

Even if the container is deleted, data stored in the my_data volume can be reused.

Common Errors and Solutions

1. permission denied Error

If you see permission denied when trying to run Docker, your user may not belong to the docker group.

Add the user to the Docker group:

sudo usermod -aG docker $USER

Log out and log back in to apply the change.

2. image not found Error

If an image has been removed from Docker Hub, specify a newer tag when pulling:

docker pull ubuntu:22.04

Specifying an explicit version ensures that the correct image is retrieved.