Elegir un comando de inicio para tu imagen de Docker

Introducción a Docker

Tim Sangster

Software Engineer @ DataCamp

¿Qué es un comando de inicio?

La imagen hello-world imprime texto y luego se detiene.

docker run hello-world
Hello from Docker!

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon created a new container from the hello-world image which runs the
    executable that produces the output you are currently reading.
 3. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.
Introducción a Docker

¿Qué es un comando de inicio?

Una imagen con python podría iniciar python al arrancar.

docker run python3-sandbox
Python 3.10.6 (main, Nov  2 2022, 18:53:38) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 
...
....
>>> exit()
repl@host:/#
Introducción a Docker

Ejecutar un comando de shell al inicio

CMD <shell-command>

La instrucción CMD:

  • Se ejecuta al iniciar la imagen.
  • No aumenta el tamaño de la imagen.
  • No añade tiempo a la construcción.
  • Si hay varias, solo la última tiene efecto.
Introducción a Docker

Uso típico

Iniciar una aplicación para ejecutar un flujo de trabajo o que acepte conexiones externas.

CMD python3 my_pipeline.py
CMD postgres

Iniciar un script que a su vez inicie varias aplicaciones

CMD start.sh
CMD python3 start_pipeline.py
Introducción a Docker

¿Cuándo se detiene?

$$

  • Imagen hello-world -> Tras imprimir texto
  • Imagen de base de datos -> Cuando la base de datos termina

$$

Una imagen más general necesita un comando de inicio más general.

  • Imagen de Ubuntu -> Cuando se cierra la shell
Introducción a Docker

Sobrescribir el comando de inicio predeterminado

Iniciar una imagen

docker run <image>

Iniciar una imagen con un comando de inicio personalizado

docker run <image> <shell-command>

Iniciar interactivamente con un comando de inicio personalizado

docker run -it <image> <shell-command>
docker run -it ubuntu bash
Introducción a Docker

Resumen

Uso Instrucción Dockerfile
Añadir un comando de shell que se ejecute al iniciar un contenedor desde la imagen. CMD <shell-command>

Uso Comando de shell
Sobrescribir el CMD definido en la imagen docker run <image> <shell-command>
Sobrescribir el CMD y ejecutar en modo interactivo docker run -it <image> <shell-command>
Introducción a Docker

¡Vamos a practicar!

Introducción a Docker

Preparing Video For Download...