C/ Condesa de Venadito, nº 528027 Madrid.
Tel.: + 34/ 91 408 78 78Fax: + 34/91 405 78 88
panel.esPanel Sistemas Informáticos, S.L.Consultoría, servicios y soluciones TI.
28/02/2018
David Vázquez Novella
1. Qué es?2. Despliegue de aplicaciones sin Docker3. Despliegue de aplicaciones con Docker4. Máquinas Virtuales vs Contenedores Docker5. Instalación6. Arquitectura7. Imágenes8. Contenedores9. Creando imágenes10. Docker Hub / Registry11. Volúmenes12. Redes13. Docker compose14. Dockerizando nuestras aplicaciones Java15. Orquestadores16. Docker en la nube
AGENDA
QUÉ ES DOCKER
https://www.docker.com (Docker, Inc)
o Proyecto de código abierto que automatiza el despliegue de aplicaciones dentro
de contenedores de software
o Supone nueva forma de empaquetar (build), distribuir (ship) y ejecutar (run) aplicaciones
o Permite empaquetar una aplicación con todas sus dependencias necesarias (servidor,
librerías, aplicaciones, etc) y ser ejecutada en múltiples entornos y plataformas
o Inicios:
Proyecto interno dentro de dotCloud (empresa enfocada a una plataforma como un
servicio - PaaS)
Liberado como código abierto en marzo de 2013
o Contribuyentes: Red Hat, IBM, Google, CiscoSystems, …
o Integración con múltiples herramientas de infraestructura: Jenkins, Ansible, Vagrant,
AWS, Google Cloud Platform, Azure, OpenStack, …
Desarrollo Integración Preproducción Producción
Tomcat 9
PostgreSQL 10
AppApp
Tomcat 9
PostgreSQL 10
App
Tomcat 8
PostgreSQL 9.5
App
Nuevo entorno Tomcat 8
PostgreSQL 9.5
App Problemas:
- Coste mantenimiento
- Coste creación nuevos entornos
- No garantía App funciona en todos igual
DESPLIEGUE DE APLICACIONESSIN DOCKER
Docker Docker
Desarrollo Integración Producción
Nuevo entorno/
Entorno local
Ventajas:
- Empaqueta aplicación con todas sus
dependencias
- Ejecución en múltiples plataformas
- Permite crear nuevos entornos
rápidamente y de forma repetible
Tomcat 9
App
PostgreSQL 10
…Tomcat 9
App
PostgreSQL 10
Tomcat 9
App
PostgreSQL 10
Docker
PostgreSQL 9.5
Tomcat 8
App
DESPLIEGUE DE APLICACIONESCON DOCKER
Máquinas Virtuales:
o Encapsula un host completo (SO + Apps)
o Imágenes de gran tamaño
o Lentas: requieren minutos para arrancar
o Acceso a recursos del host mediante el hipervisor
o Imágenes no son portables entre hipervisores
o Proveen entorno con más recursos de los que necesita nuestra aplicación
o Gran uso de recursos (procesador, memoria)
o Mayor aislamiento de seguridad por defecto
Contenedores:
o Comparten el kernel del host, no necesario otro SO completo
o Imágenes de menor tamaño
o Rápidos: sólo ejecutan procesos de aplicación
o Bajo uso de recursos (procesador, memoria)
o Menor aislamiento de seguridad por defecto
Máquinas Virtuales vs Docker
Instalación
o Windows 10Docker for Windows: https://docs.docker.com/docker-for-windows/install/
o Microsoft Windows Server 2016:https://docs.docker.com/install/windows/docker-ee/
o Para Windows anteriores: Docker Toolbox
o Docker for Mac (Mac hardware 2010+ y macOS Yosemite 10.10.3+)https://docs.docker.com/docker-for-mac/install/
o Para Mac anteriores: Docker Toolbox
o Ubuntu: https://docs.docker.com/install/linux/docker-ce/ubuntu/o Debian: https://docs.docker.com/install/linux/docker-ce/debian/o Fedora: https://docs.docker.com/install/linux/docker-ce/fedora/o CentOS: https://docs.docker.com/install/linux/docker-ce/centos/o …
ArquitecturaConceptos básicos
o Imagen: Contiene una distribución de SO y una determinada configuración de
paquetes, aplicaciones y datos determinados por los creadores de la imagen.
o Contenedor: Es una instancia de una imagen concreta ejecutada como un proceso
aislado en una máquina concreta (Docker Host).
o Docker Host: es la máquina que tiene instalado Docker engine (daemon) y ejecuta los
comandos que recibe del Docker Client para gestionar imágenes y ejecutar
contenedores.
o Docker Client: herramienta cliente para gestionar imágenes y ejecutar contenedores
en el Docker Host. (puede residir en el Docker Host o en otra máquina).
o Docker Hub / Registry: repositorios de imágenes (públicos o privados), accesibles
mediante CLI, interfaz web y API REST.
o Docker compose: herramienta para ejecutar múltiples contenedores de forma
coordinada.
Docker IMAGEScomandos
docker images - List images in local registrydocker pull - Pull an image or a repository from a registrydocker ispect - Return information on Docker objects (images, containers)docker history - Show the history of an image
docker build - Build an image from a Dockerfile
docker save - Save one or more images to a tar archivedocker load - Load an image from a tar archive or STDINdocker export - Export a container's filesystem as a tar archivedocker import - Import the contents from a tarball to create a filesystem image
docker rmi - Remove one or more images
docker tag - Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
docker run
docker run - run a container
-d run container in background--rm remove container automatically after it exits- e set environment variable-it interactive mode. Connect the container to terminal--name assign a name to the container-p xxxx:yy expose port xxxx externally (docker host) and map to container port yy-v create a host mapped volumen inside the container
docker ps - List running containers (-a list all: running and stopped)
docker inspect - return information on Docker objects (images, containers)
docker start - start one or more stopped containersdocker stop - stop the process run inside the container in the correct waydocker kill - send a kill signal to the process
Docker CONTAINERScomandos
docker rm - Remove one or more containers
docker exec - Run a command in a running container (-ti interative mode)
docker cp - Copy files/folders between a container and the local filesystem
docker logs - Fetch the logs of a container
-f follow log output--tail <n> number of lines to show from the end of the logs
docker stats - Display a live stream of container(s) resource usage statistics
Docker CONTAINERScomandos
Volúmenes
Se usan para persistir datos fuera de los contenedores.
Mejor opción que persistir los datos dentro del contenedor:
- No incrementamos el tamaño del contenedor
- El contenido del volúmen persiste independientemente del ciclo de vida
del contenedor
- Podemos compartir el volúmen con más contenedores
docker run -d -p 80:8080 -v d:/html:/usr/local/tomcat/webapps/examples/html tomcat
Building Docker IMAGES
Commit(guardar un contenedor como una imagen nueva)
Commands:docker commit tomcat david/mitomcat:1.0docker commit –m “commit message” –a “author” tomcat david/mitomcat:1.0
Building Docker IMAGES
Dockerfile
Commands:docker build .docker build -t myrepo/myapp .docker build -t myrepo/my-imagename -f /path/Dockerfile
Dockerfilecommand
Purpose Example
FROM sets the Base Image for subsequent instructions FROM Ubuntu
LABELadds metadata to an image. An image can have more than one label.
LABEL version="1.0“LABEL description="This image”
WORKDIRsets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow it in the Dockerfile
USER
sets the user name (or UID) to use when running the image and for any RUN, CMD and ENTRYPOINT instructions that follow it in the Dockerfile
COPYcopies new files or directories from <src> and adds them to the filesystem of the container at the path <dest>
COPY .bash_profile /home
ADD
copies new files, directories or remote file URLs from <src> and adds them to the filesystem of the image at the path <dest>. Difference with copy: ADD allows <src> to be an URLand If the <src> parameter of ADD is a compressed archive, it will be unpacked
https://docs.docker.com/engine/reference/builder
Building Docker IMAGES
Dockerfile
Dockerfilecommand
Purpose Example
ENVSets a environment variable. This value will be in the environment of all “descendant” Dockerfile commands
ENV foo=/barWORKDIR ${foo} # WORKDIR /bar
ARG
variable that users can pass at build-time to the builder with the docker build command using the --build-arg<varname>=<value> flag
RUN
execute any commands in a new layer on top of the current image and commit the results.The resulting committed image will be used for the next step in the Dockerfile
RUN apt-get update
CMD
provide defaults for an executing containercan only be one CMD instruction in a DockerfileThese defaults can include an executable, or they can omit the executable, in which case you must specify an ENTRYPOINT instruction as well
CMD ["/bin/echo", "hello world"]
https://docs.docker.com/engine/reference/builder
Building Docker IMAGES
Dockerfile
Dockerfilecommand
Purpose Example
ENTRYPOINT
configure a container that will run as an executable. Command line arguments to docker run <image> will be appended after all elements in an exec form ENTRYPOINT, and will override all elements specified using CMD. This allows arguments to be passed to the entry point
EXPOSE
informs Docker that the container listens on the specified network ports at runtime.The EXPOSE instruction does not actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container, about which ports are intended to be published
EXPOSE 8093
VOLUME
creates a mount point with the specified name and marks it as holding externally mounted volumes from native host or other containers.
HEALTHCHECK
tells Docker how to test a container to check that it is still working. For example, to check every five minutes or so that a web-server is able to serve the site’s main page within three seconds:
HEALTHCHECK --interval=5m --timeout=3s \CMD curl -f http://localhost/ || exit 1
Building Docker IMAGES
Dockerfile
Docker Hub/Registry
docker pull - pull an image or a repository from a registrydocker pull alpine:3.4
docker tag - retag a local image with a new image name and tagdocker tag alpine:3.4 myrepo/myalpine:3.4
docker login - log in to a Docker registry (Docker hub by default)docker login my.registry.com:8000
docker push - push an image or a repository from a registrydocker push myrepo/myalpine:3.4
docker logout - log out from a Docker registry
https://hub.docker.com/
Redes
docker network create Create a network
docker network connect Connect a container to a network
docker network disconnect Disconnect a container from a network
docker network inspectDisplay detailed information on one or more networks
docker network ls List networks
docker network prune Remove all unused networks
docker network rm Remove one or more networks
https://docs.docker.com/engine/reference/commandline/network/
RedesEjemplo: Aplicación compuesta por front-end web conectado con una base de datos. Front-end accessible en localhost:8000
docker network create -d bridge mynetworkdocker run -d --net mynetwork --name db postgresdocker run -d --net mynetwork -e DB=db -p 8000:5000 --name web mywebapp
Docker Compose
docker-compose.yml docker-compose up
https://docs.docker.com/compose/
Herramienta para ejecutar múltiples contenedores de forma coordinada
Facilita la configuración y ejecución de aplicaciones compuestas por múltiples módulos
en contenedores
docker-compose config - validate and view the compose file docker-compose images - list images (running)
docker-compose up - create and start containers-d run containers in the background-f specify docker-compose file to be used--scale <service>=<num> scale a service
docker-compose down - stop and remove containers, networks, images and volumes
docker-compose ps - list containers docker-compose top - display de running processes
docker-compose scale - set number of containers for a servicedocker-compose scale chrome=3
docker-compose exec - execute a command in a running containerdocker-compose exec <service> topdocker-compose exec <service> /bin/sh
…
Docker Composecommands
Docker Composedocker-compose file
https://docs.docker.com/compose/compose-file/
docker-composefile command
Purpose
version Version of docker-compose file
services Tag to start service definitions
image Specify the image to start the container from.
container_name Specify a custom container name, rather than a generated default name
portsExpose ports. Either specify both ports (HOST:CONTAINER), or just the
container port (an ephemeral host port is chosen).
depends_on Express dependency between services
environment Add environment variables
scale Specify the default number of containers to deploy for this service
networks Networks to join
volumes Mount host folders or named volumes.
…
Dockerizando nuestras aplicaciones Java
Plugins de Maven para Docker:
- Específicos:
dockerfile-maven-plugin https://github.com/spotify/dockerfile-maven
docker-maven-plugin https://github.com/fabric8io/docker-maven-plugin
- Generales
exec-maven-plugin http://www.mojohaus.org/exec-maven-plugin/
Docker en la Nube
Soportado por todos los principales proveedores en la nube
Docker Container Service
EC2 Container Service Google Container Engine Azure Container Service
Bluemix Containers Container Platform
Top Related