Si has trabajado con docker, o si lo has probado, seguro que te has dado cuenta de la cantidad de comandos que tiene y la cantidad de opciones posibles. Para simplificarme un poco la vida he estado buscando información y lo que más util me resulta es crear un pequeño Makefile con los comandos que más utilizo.

Así que hoy voy a contar algunos trucos y consejos sobre Makefiles y para que veáis la cantidad de comandos que hay aquí os dejo la lista:
Commands: attach Attach local standard input, output, and error streams to a running container build Build an image from a Dockerfile commit Create a new image from a container's changes cp Copy files/folders between a container and the local filesystem create Create a new container deploy Deploy a new stack or update an existing stack diff Inspect changes to files or directories on a container's filesystem events Get real time events from the server exec Run a command in a running container export Export a container's filesystem as a tar archive history Show the history of an image images List images import Import the contents from a tarball to create a filesystem image info Display system-wide information inspect Return low-level information on Docker objects kill Kill one or more running containers load Load an image from a tar archive or STDIN login Log in to a Docker registry logout Log out from a Docker registry logs Fetch the logs of a container pause Pause all processes within one or more containers port List port mappings or a specific mapping for the container ps List containers pull Pull an image or a repository from a registry push Push an image or a repository to a registry rename Rename a container restart Restart one or more containers rm Remove one or more containers rmi Remove one or more images run Run a command in a new container save Save one or more images to a tar archive (streamed to STDOUT by default) search Search the Docker Hub for images start Start one or more stopped containers stats Display a live stream of container(s) resource usage statistics stop Stop one or more running containers tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE top Display the running processes of a container unpause Unpause all processes within one or more containers update Update configuration of one or more containers version Show the Docker version information wait Block until one or more containers stop, then print their exit codes
Objetivo
Crear un pequeño archivo con los comandos más utilizados de docker y que podamos llevarlo de proyecto en proyecto sin que tengamos que configurar o memorizar excesivos comandos
Instalación
Con este objetivo en mente y después de probar varias opciones: tener un txt los comandos, un fichero bash,.. lo mejor es tener un makefile por una razón: es simple, sólo necesitas tener instalado make en MacOs y además la sintaxis es muy clara. Para instalarlo con brew:
brew install make
Estructura
Los makefiles tienen un formato bastante sencillo
objetivo: dependencias comandos
el «objetivo«es el comando que vamos a teclear, las dependencias pueden utilizarse para concatenar objetivos y los «comandos» que es lo que realmente se ejecuta.
Comandos
Por ejemplo, este Dockerfile es el que utilizo para hacer katas.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
FROM phpstorm/php-71-cli-xdebug | |
MAINTAINER Jesus Lopez <jeslopcru@gmail.com> | |
# Composer and dependencies | |
RUN apt-get update && \ | |
apt-get install git unzip -y | |
RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" && \ | |
php composer-setup.php && \ | |
php -r "unlink('composer-setup.php');" && \ | |
mv composer.phar /usr/local/bin/composer | |
# Volume to have access to the source code | |
VOLUME ["/opt/project"] | |
WORKDIR /opt/project |
Si queremos hacer un build para crear una imagen y poder utilizarla tenemos que ejecutar siempre el mismo comando.
Pues un makefile para hacer el build de la imagen sería algo así:
build: ## Build a Dockerimage docker build -t my-php .
Tan simple como estas 2 lineas. Si creamos un fichero llamado Makefile, le añadimos estas lineas y listo. Lo que viene después de las ## es un comentario para saber que hace el comando (ya verás más adelante)
Ahora para montar la imagen solo tendremos que ejecutar en un terminal:
$ make build
y ya tendremos la imagen lista.
Si queremos instalar las dependencias con composer, tenemos que ejecutar la imagen para levantar un container y dentro dentro de ese container el comando de composer install. Pues un makefile con todo esto sería algo así:
install: ## install dependencies with "composer install" docker run --rm -it -v $(shell pwd):/opt/project my-php composer install
Ahora con tan solo ejecutar el siguiente comando se instalan todas las dependencias de composer.
$ make install
Si lo que queremos es ejecutar test, pues tenemos algo como esto
phpunit: ## run phpunit test docker run --rm -it -v $(shell pwd):/opt/project my-php ./vendor/bin/phpunit
Extras
El comando @ de Makefile es el comando que va a ejecutarse por defecto si ejecutamos en un terminal make
Aquí lo mejor sería tener un comando que listase todos los objetivos que hay en el fichero Makefile junto con una pequeña descripción 😉
Para ello tenemos que añadir esto a nuestro makefile:
help: ## Print this help.help: @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}'
Si lo unimos todo, tendremos un makefile como este:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.PHONY: help | |
help: ## Print this help. | |
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}' | |
build: ## Build a dockerimage | |
docker build -t my-php . | |
install: ## install dependencies with "composer install" | |
docker run –rm -it -v $(shell pwd):/opt/project my-php composer install | |
composer: ## run a composer command with an argument arg | |
docker run –rm -it -v $(shell pwd):/opt/project my-php composer $(arg) | |
phpunit: ## run phpunit test | |
docker run –rm -it -v $(shell pwd):/opt/project my-php ./vendor/bin/phpunit | |
shell: ## shell inside docker container | |
docker run –rm -it -v $(shell pwd):/opt/project my-php /bin/bash |
Sencillo, útil y práctico que podemos llevarnos a cualquier proyecto.
De la misma manera, si queremos mejorar este archivo, por ejemplo pudiendo pasar variables al make podríamos hacerlo así:
paso: ## pasar variables: @echo $(arg)
Este comando, lo único que hace es imprimir por pantalla la variable que le pasemos. Para utilizarlo sería algo así:
$ make paso arg="hola mundo" hola mundo
Así que podemos por ejemplo tener un comando para composer algo así
composer: ## run a composer command with an argument arg docker run --rm -it -v $(shell pwd):/opt/project my-php composer $(arg)
Para utilizarlo solo tenemos que escribir
$ make composer arg="validate"
Con esto ya tenemos todos ya tenemos todos los comandos que utilizamos habitualmente con docker automatizados de una manera simple y sencilla con un Makefile. Seguro que me dejo atrás algún comando o algún truco, escribe un comentario para compartirlo conmigo. ¡Seguro que entre todos podemos conseguir un buen Makefile!
Buen post, Makefile es super útil para estas cosas. También se puede declarar variables para reutilizar entre los comandos. Consulta has logrado crear algo así como un Makefile.local para poder setear variables que solo se usaran en local. Gracias.
Me gustaMe gusta