Creating your own Docker images

Introduction to Docker

Tim Sangster

Software Engineer @ DataCamp

Creating images with Dockerfiles

Dockerfiles are build to get a Docker Images which when run create a container.

Introduction to Docker

Starting a Dockerfile

A Dockerfile always start from another image, specified using the FROM instruction.

FROM postgres
FROM ubuntu
FROM hello-world
FROM my-custom-data-pipeline
FROM postgres:15.0
FROM ubuntu:22.04
FROM hello-world:latest
FROM my-custom-data-pipeline:v1
Introduction to Docker

Building a Dockerfile

Building a Dockerfile creates an image.

docker build /location/to/Dockerfile
docker build .
[+] Building 0.1s (5/5) FINISHED
 => [internal] load build definition from Dockerfile
 => => transferring dockerfile: 54B
...
 => CACHED [1/1] FROM docker.io/library/ubuntu
 => exporting to image
 => => exporting layers
 => => writing image sha256:a67f41b1d127160a7647b6709b3789b1e954710d96df39ccaa21..
Introduction to Docker

Naming our image

In practice we almost always give our images a name using the -t flag:

docker build -t first_image .
...
=> => writing image sha256:a67f41b1d127160a7647b6709b3789b1e954710d96df39ccaa21..
=> => naming to docker.io/library/first_image 
docker build -t first_image:v0 .
=> => writing image sha256:a67f41b1d127160a7647b6709b3789b1e954710d96df39ccaa21..
=> => naming to docker.io/library/first_image:v0
Introduction to Docker

Customizing images

RUN <valid-shell-command>
FROM ubuntu
RUN apt-get update
RUN apt-get install -y python3

Use the -y flag to avoid any prompts:

...
After this operation, 22.8 MB of additional disk space will be used.
Do you want to continue? [Y/n]
Introduction to Docker

Building a non-trivial Dockerfile

When building an image Docker actually runs commands after RUN

Docker running RUN apt-get update takes the same amount of time as us running it!

root@host:/# apt-get update
Get:1 http://ports.ubuntu.com/ubuntu-ports jammy InRelease [270 kB]
...
Get:17 http://ports.ubuntu.com/ubuntu-ports jammy-security/restricted arm64 Pack..
Fetched 23.0 MB in 2s (12.3 MB/s)                          
Reading package lists... Done
Introduction to Docker

Summary

Usage Dockerfile Instruction
Start a Dockerfile from an image FROM <image-name>
Add a shell command to image RUN <valid-shell-command>
Make sure no user input is needed for the shell-command. RUN apt-get install -y python3

Usage Shell Command
Build image from Dockerfile docker build /location/to/Dockerfile
Build image in current working directory docker build .
Choose a name when building an image docker build -t first_image .
Introduction to Docker

Let's practice!

Introduction to Docker

Preparing Video For Download...