Crea tus propias imágenes de Docker

Introducción a Docker

Tim Sangster

Software Engineer @ DataCamp

Crear imágenes con Dockerfiles

Los Dockerfiles se crean para obtener imágenes de Docker que, al ejecutarse, crean un contenedor.

Introducción a Docker

Iniciar un Dockerfile

Un Dockerfile siempre parte de otra imagen, indicada con la instrucción FROM.

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
Introducción a Docker

Crear un Dockerfile

Crear un Dockerfile genera una imagen.

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..
Introducción a Docker

Nombrar la imagen

En la práctica, casi siempre damos un nombre a las imágenes con la opción -t:

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
Introducción a Docker

Personalizar imágenes

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

Usa la opción -y para evitar prompts:

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

Crear un Dockerfile no trivial

Al construir una imagen, Docker ejecuta los comandos tras RUN

Que Docker ejecute RUN apt-get update tarda lo mismo que si lo hacemos nosotros.

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
Introducción a Docker

Resumen

Uso Instrucción Dockerfile
Empezar un Dockerfile desde una imagen FROM <image-name>
Añadir un comando de shell a la imagen RUN <valid-shell-command>
Asegura que no pida entrada del usuario. RUN apt-get install -y python3

Uso Comando de shell
Crear imagen desde Dockerfile docker build /location/to/Dockerfile
Crear imagen en el directorio actual docker build .
Elegir nombre al crear una imagen docker build -t first_image .
Introducción a Docker

¡Vamos a practicar!

Introducción a Docker

Preparing Video For Download...