Skip to content

Instantly share code, notes, and snippets.

@AlexAlonsoMontero
Last active September 23, 2024 08:08
Show Gist options
  • Save AlexAlonsoMontero/cb04435c56084e14e3e44af88ea85e91 to your computer and use it in GitHub Desktop.
Save AlexAlonsoMontero/cb04435c56084e14e3e44af88ea85e91 to your computer and use it in GitHub Desktop.
Guía básica Docker

DOCKER (Manual básico)

INSTLACIÓN LINUX

  • Instalación requisitos previos
sudo apt install apt-transport-https ca-certificates curl software-properties-common
  • Añadir clave GPG para docker
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
  • Añadir Docker a repositorio APT
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable"
sudo apt update
  • Verificar que la instalación se realizará desde el repositorio de docker y no el de ubuntu
apt-cache policy docker-ce
  • Resultado del comando ( puede variar la versión )
docker-ce:
  Instalados: (ninguno)
  Candidato:  5:27.1.2-1~ubuntu.20.04~focal
  Tabla de versión:
     5:27.1.2-1~ubuntu.20.04~focal 500
        500 https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
     5:27.1.1-1~ubuntu.20.04~focal 500
  • Comando de instalación
sudo apt install docker-ce
  • Verificar si docker esta instalado y en ejecución
sudo systemctl status docker

COMANDOS DOCKER

  • Escribiendo docker en terminal, se imprimirán los subcomandos
docker

Usage:  docker [OPTIONS] COMMAND

A self-sufficient runtime for containers

Common Commands:
  run         Create and run a new container from an image
  exec        Execute a command in a running container
  ps          List containers
  build       Build an image from a Dockerfile
  pull        Download an image from a registry
  push        Upload an image to a registry
  images      List images
  login       Log in to a registry
  logout      Log out from a registry
  search      Search Docker Hub for images
  version     Show the Docker version information
  info        Display system-wide information

Management Commands:
  builder     Manage builds
  buildx*     Docker Buildx
  checkpoint  Manage checkpoints
  compose*    Docker Compose
  container   Manage containers
  context     Manage contexts
  image       Manage images
  manifest    Manage Docker image manifests and manifest lists
  network     Manage networks
  plugin      Manage plugins
  system      Manage Docker
  trust       Manage trust on Docker images
  volume      Manage volumes

Swarm Commands:
  config      Manage Swarm configs
  node        Manage Swarm nodes
  secret      Manage Swarm secrets
  service     Manage Swarm services
  stack       Manage Swarm stacks
  swarm       Manage Swarm

Commands:
  attach      Attach local standard input, output, and error streams to a running container
  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
  diff        Inspect changes to files or directories on a container's filesystem
  events      Get real time events from the server
  export      Export a container's filesystem as a tar archive
  history     Show the history of an image
  import      Import the contents from a tarball to create a filesystem image
  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
  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
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  rmi         Remove one or more images
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  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
  wait        Block until one or more containers stop, then print their exit codes
  • Ayuda de un comando en concreto
docker docker-subcommand --help
  • Información de cocker respecto al sistema
docker info

IMAGENES EN DOCKER

docker pull image-name
  • Listar imagenes descargadas
docker images

REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
ubuntu       latest    edbfe74c41f8   3 weeks ago   78.1MB
  • Descargar una imagen con tag:
docker pull image-name tag
  • Crear una nueva imgaen desde un contenedor ( 2 opciones )
sudo docker commit container-id new-image-name
docker commit -m "What you did to the image" -a "Author Name" container_id repository/new_image_name
  • Eliminar imagenes pendientes
docker rmi Image Image

COMANDOS CONTENEDORES

  • Crear contenedor
docker run image-name
  • Ver contenedores en ejecución
docker ps
  • Ver contenedores en que se han creado y su status
docker ps -a

CONTAINER ID   IMAGE         COMMAND    CREATED         STATUS                     PORTS     NAMES
7a36deff1639   hello-world   "/hello"   3 minutes ago   Exited (0) 3 minutes ago             tender_cartwright

  • Borrar contenedor
docker rm container-id
  • Listar contenido de un contenedor:
docker run docker-image ls
  • Parar un contenedor en ejecución ( 2 opciones)
docker stop container-name
docker stop container-id
  • Ejecutar contenedor
docker run container-name
  • Arrancar contenedor
sudo docker start container-id
  • Parar contenedor
sudo docker stop container-id
  • Ejecutar contenedor e interactuar con el
docer run -i -t container-name
  • Ejecutar contenedor y asignar nombre
docker run --name name -it container-name
  • Conectarse a contenedor en ejecución
sudo docker attach container-id

EJEMPLO:

  • Ejecutar contenedor ubuntu en consola y ejecutar comandos dentro de la imagen

docker run -i -t ubuntu bash

  • Ejecutar contenedor ubuntu y asignar nombre
docker run --name contenedor-prueba -it ubuntu
  • Salir de un contenedor interactivo sin cerrarlo teclas Ctrl + p + q

PERSONALIZAR CONTENEDORES

  • Trabajare mediante un ejemplo con ubuntu

  • Iniciar contenedor con ubuntu:

docker run start container-id
  • Actualizamos:
apt update
apt install nano
  • Ejecutamos nano
nano

BORRADO

  • Eliminar recursos no asociados a un contenedor
docker system prune
  • Eliminar todos los recursos
docker system prune -a

OBJETOS DOCKER

  • Dockerfile
  • Image
  • Container
  • Network
  • Storage volumes
  • Plugins / Add-ons

DOCKER FILE

  • Cear el fichero siempre con nombre Dockerfile

Listado comandos

  • from - Imgen en la que nos vamos a basar
  • run - Permite ejecutar comandos en la imagen base antes de ser creada
  • add/copy - Añadir o copiar archivos desde el equipo local
  • expose: Permite exponer un puerto para el contenedor
  • cmd: Acción a ejecutar al crear el contenedor (finalidad)

Ejemplo Dockerfile

FROM debian:buster-slim
MAINTAINER Alejandro Alonso "[email protected]"
RUN apt-get update  && apt-get install -y  apache2
COPY index.html /var/www/html/
CMD ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"]

Crear imagen desde fichero docker

docker build -t nombre-imagen ruta
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment