Creación de imágenes de contenedor con Docker#
Cuenta en Docker Hub#
Crea una cuenta en Docker Hub
Note
- Todos los integrantes del equipo deben crear una cuenta en DockerHub
- Anota todos los nombres de usuario (Docker ID) en tu reporte
Página de registro de Docker Hub |
---|
![]() |
Instalación de Docker Desktop#
Instala Docker Desktop en tu computadora personal
- https://www.docker.com/products/docker-desktop/
- https://docs.docker.com/desktop/
- https://www.docker.com/blog/getting-started-with-docker-desktop/
Note
En GNU/Linux opcionalmente puedes instalar el demonio de docker (sin interfaz gráfica) Para esto sigue las instrucciones de Docker Engine para tu distribución de GNU/Linux
Prueba de un contenedor#
Ejecuta el contenedor hello-world
para verificar que Docker está instalado correctamente
usuario@laptop ~ % docker run -it hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
7050e35b49f5: Pull complete
Digest: sha256:80f31da1ac7b312ba29d65080fddf797dd76acfb870e677f390d5acba9741b17
Status: Downloaded newer image for hello-world:latest
Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
(arm64v8)
3. The Docker daemon created a new container from that image which runs the
executable that produces the output you are currently reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
to your terminal.
To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash
Share images, automate workflows, and more with a free Docker ID:
https://hub.docker.com/
For more examples and ideas, visit:
https://docs.docker.com/get-started/
Descargar una imagen de contenedor#
Descarga una imagen de contenedor del registry docker.io
Note
Normalmente este paso se puede omitir porque la imagen se descarga cuando el contenedor se ejecuta o se construye
usuario@laptop ~ % docker pull nginx:1.23-alpine
1.23-alpine: Pulling from library/nginx
c41833b44d91: Pull complete
2c2c9b85ac58: Pull complete
40f94fa36194: Pull complete
ae26f20697dc: Pull complete
e4fa283fba0e: Pull complete
4c53b6cdc37b: Pull complete
7bcac465295e: Pull complete
Digest: sha256:02ffd439b71d9ea9408e449b568f65c0bbbb94bebd8750f1d80231ab6496008e
Status: Downloaded newer image for nginx:1.23-alpine
docker.io/library/nginx:1.23-alpine
Ejecutar un contenedor con un servidor web#
Ejecuta la imagen de contenedor que acabas de descargar
- La opción
-it
indica que se muestre en pantalla la salida del proceso que se ejecuta en contenedor - La opción
-p 8080:80
indica que se redireccionará el puerto8080
del equipo físico al puerto80
del contenedor
Note
Usualmente se puede escribir el nombre corto del contenedor (nginx:1.23-alpine
), pero es recomendable escribir la ruta completa de la imagen para evitar ambigüedades entre registries
usuario@laptop ~ % docker run -it -p 8080:80 docker.io/library/nginx:1.23-alpine
Unable to find image 'nginx:1.23-alpine' locally
1.23-alpine: Pulling from library/nginx
c41833b44d91: Pull complete
2c2c9b85ac58: Pull complete
40f94fa36194: Pull complete
ae26f20697dc: Pull complete
e4fa283fba0e: Pull complete
4c53b6cdc37b: Pull complete
7bcac465295e: Pull complete
Digest: sha256:02ffd439b71d9ea9408e449b568f65c0bbbb94bebd8750f1d80231ab6496008e
Status: Downloaded newer image for nginx:1.23-alpine
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2023/05/22 04:32:59 [notice] 1#1: using the "epoll" event method
2023/05/22 04:32:59 [notice] 1#1: nginx/1.23.4
2023/05/22 04:32:59 [notice] 1#1: built by gcc 12.2.1 20220924 (Alpine 12.2.1_git20220924-r4)
2023/05/22 04:32:59 [notice] 1#1: OS: Linux 5.15.49-linuxkit
2023/05/22 04:32:59 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2023/05/22 04:32:59 [notice] 1#1: start worker processes
2023/05/22 04:32:59 [notice] 1#1: start worker process 30
2023/05/22 04:32:59 [notice] 1#1: start worker process 31
2023/05/22 04:32:59 [notice] 1#1: start worker process 32
2023/05/22 04:32:59 [notice] 1#1: start worker process 33
...
Acceder al contenedor del servidor web#
Abre otra terminal y lista los contenedores que se están ejecutando
- Visualiza la columna
PORTS
y verifica que indique que el puerto8080
del equipo físico se redirige al puerto80
del contenedor0.0.0.0:8080->80/tcp
para las conexiones IPv4:::8080->80/tcp
para las conexiones IPv6
usuario@laptop ~ % docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
68a8a97ddda5 nginx:1.23-alpine "/docker-entrypoint…" 5 seconds ago Up 4 seconds 0.0.0.0:8080->80/tcp raccoon_city
Accede a la URL del contenedor para verificar que el servidor web responde
usuario@laptop ~ % curl -fsSL http://localhost:8080/ | egrep '</?title>'
<title>Welcome to nginx!</title>
Abre un navegador web y accede a la URL del contenedor
Página web del contenedor nginx |
---|
![]() |
Crear imagenes de contenedor#
Iniciar sesión en el registry Docker Hub#
Utiliza el siguiente comando para iniciar sesión en Docker Hub y que puedas enviar las imagenes de contenedor que construyas al registry.
usuario@laptop ~ % docker login docker.io
Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one.
Username: tonejito
Password:
WARNING! Your password will be stored unencrypted in /home/usuario/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store
Login Succeeded
Warning
- Tu contraseña se guardará en texto plano en el archivo
~/.docker/config.json
. - Es RECOMENDABLE que configures un mecanismo para que se guarde de manera cifrada en tu equipo
Sintaxis de Dockerfile
#
Esta es la sintaxis de un Dockerfile
que utiliza BuildKit y algunas características modernas como heredoc en el comando COPY
Cada acción se explica en un comentario
Warning
- Asegúrate de especificar la primer línea
# syntax=docker/dockerfile:1.4
(con el símbolo#
) para utilizar las características avanzadas de BuildKit - En caso de que tu versión de Docker no soporte BuildKit, utiliza la otra opción en el
Dockerfile
# syntax=docker/dockerfile:1.4
# La primer línea permite utilizar características avanzadas de BuildKit
# Especifica qué contenedor se utilizará como base para la nueva imagen
FROM docker.io/library/nginx:1.23-alpine AS nginx
# Declara una variable de entorno para utilizarla después en algún comando
ENV NGINX_ROOT=/usr/share/nginx/html
# Crea la página de índice para NGINX
# Es necesaria la primer línea (syntax=docker/...) para hacer uso de esta variante de COPY
COPY <<EOF ${NGINX_ROOT}/index.html
<html>
<head>
<title>Hello world!</title>
</head>
<body>
<h1>It works!</h1>
</body>
</html>
EOF
- Revisa el contenido de los siguientes archivos
Dockerfile
- Modificalos haciendo comentarios línea por línea explicando las acciones realizadas
-
Anexa los archivos modificados a tu reporte
files/linux-doc/Dockerfile
yfiles/tareas-redes/Dockerfile
Dockerfile
para el contenedorlinux-doc
- Tal vez necesites el archivo
apt-conf-99-local.conf
- Tal vez necesites el archivo
Dockerfile
para el contenedortareas-redes
- Modifica las variables de entorno
GIT_PROJECT
,GIT_REPO
yGIT_BRANCH
de tal manera queGITLAB_URL
apunte al repositorio donde tu equipo envía las tareas de la materia
- Modifica las variables de entorno
Construir imagenes de contenedor#
Utiliza docker build
para construir la imagen del contenedor, verifica que el TAG
corresponda a tu nombre de usuario y el contenedor linux-doc
o tareas-redes
según sea el caso
Note
- Se recomienda utilizar la opción
--progress plain
para capturar toda la salida dedocker build
- Guarda esta salida en los archivos
files/linux-doc/build-output.txt
yfiles/tareas-redes/build-output.txt
- Anexa estos archivos a tu reporte
Warning
- Necesitas construir las imagenes de contenedor en un equipo con arquitectura
x86_64
(también conocida comoamd64
) - Las imágenes no podrán ser ejecutadas en el cluster de Kubernetes en Azure si se construyen en una computadora con procesador
ARM
porque la máquina virtual de Azure tiene arquitecturax86_64
usuario@laptop ~ % TAG=tonejito/hello-nginx
usuario@laptop ~ % docker build --progress plain -t "${TAG}" ./
#1 [internal] load .dockerignore
#1 transferring context: 2B done
#1 DONE 0.0s
#2 [internal] load build definition from Dockerfile
#2 transferring dockerfile: 308B done
#2 DONE 0.0s
#3 resolve image config for docker.io/docker/dockerfile:1.4
#3 DONE 0.6s
#4 docker-image://docker.io/docker/dockerfile:1.4@sha256:9ba7531bd80fb0a858632727cf7a112fbfd19b17e94c4e84ced81e24ef1a0dbc
#4 CACHED
#5 [internal] load metadata for docker.io/library/nginx:1.23-alpine
#5 DONE 0.0s
#6 [internal] preparing inline document
#6 CACHED
#7 [1/2] FROM docker.io/library/nginx:1.23-alpine
#7 DONE 0.0s
#8 [2/2] COPY <<EOF /usr/share/nginx/html/index.html
#8 DONE 0.0s
#9 exporting to image
#9 exporting layers 0.0s done
#9 writing image sha256:7bc863031bee63b0aaf1c6ce9aa641213bc5988cefc784aa520e648b3617d9dc done
#9 naming to docker.io/tonejito/hello-nginx done
#9 DONE 0.0s
Lista las imagenes de contenedor#
usuario@laptop ~ % docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
tonejito/tareas-redes latest 93a5bb20db56 5 minutes ago 41.9 MB ⬅️
tonejito/linux-doc latest ce93e6541728 8 minutes ago 188.0 MB ⬅️
tonejito/hello-nginx latest 7bc863031bee 11 minutes ago 40.6 MB ⬅️
tonejito/hello-httpd latest 8c14047e1c63 13 minutes ago 68.4 MB
debian 11 af5aac46f628 2 weeks ago 118.0 MB
python 3.11-alpine f03ab8864405 11 days ago 57.4 MB
nginx 1.23-alpine 510900496a6c 7 weeks ago 40.6 MB
httpd 2.4-alpine 65e63686adc8 10 days ago 68.4 MB
Enviar las imagenes de contenedor al registry#
Utiliza docker push
para enviar tus imagenes de contenedor linux-doc
y tareas-redes
al registry Docker Hub
Note
- Guarda esta salida en los archivos
files/linux-doc/push-output.txt
yfiles/tareas-redes/push-output.txt
- Anexa estos archivos a tu reporte
usuario@laptop ~ % TAG=tonejito/hello-nginx
usuario@laptop ~ % docker push "${TAG}"
Using default tag: latest
The push refers to repository [docker.io/tonejito/hello-nginx]
e747e9c4bf58: Pushed
363722710bd8: Mounted from library/nginx
fbebe8ba7bed: Mounted from library/nginx
363858148796: Mounted from library/nginx
7e1b91127bea: Mounted from library/nginx
2749f4c7cb99: Mounted from library/nginx
09353074bdde: Mounted from library/nginx
26cbea5cba74: Mounted from library/nginx
latest: digest: sha256:658165388b9c111924dc7b82fabd028f07c3fbee1a7e009741a11fa7b0779d33 size: 1988
Verifica los cambios realizados#
Revisa que tus imagenes de contenedor linux-doc
y tareas-redes
aparezcan en tu cuenta de usuario en Docker Hub
Imagenes de contenedor en Docker Hub |
---|
![]() |
Warning
- Necesitas construir las imagenes de contenedor en un equipo con arquitectura
x86_64
(también conocida comoamd64
) - Las imágenes no podrán ser ejecutadas en el cluster de Kubernetes en Azure si se construyen en una computadora con procesador
ARM
porque la máquina virtual de Azure tiene arquitecturax86_64
Danger
- Verifica que TODAS las imagenes de contenedor esten presentes antes de continuar con la siguiente sección
Note
- Continúa en la siguiente página cuando hayas terminado de construir las imagenes de contenedor y las hayas subido a Docker Hub
⇦ | ⇧ | ⇨ |
---|---|---|
Página anterior | Arriba | Página siguiente |