• ¡Obtenga la seguridad de la aplicación de la manera correcta! Detectar, proteger, monitorear, acelerar y más ...
  • Mientras trabaja en proyectos de Docker, la mayoría de las veces, las imágenes de Docker existentes no cumplirán con sus requisitos.

    Aquí es donde entra en escena Dockerfile; le ayudará a crear imágenes personalizadas de Docker. Por lo tanto, conocer Dockerfile es esencial.

    ¿Qué es Dockerfile?

    Es un archivo de texto simple con un conjunto de comandos o instrucciones. Estos comandos / instrucciones se ejecutan sucesivamente para realizar acciones en la imagen base para crear una nueva imagen de la ventana acoplable.

    comentarios y comandos + argumentos son dos tipos de bloques de línea principal en la sintaxis de Dockerfile

    Sintaxis de comentarios

    #Line blocks used for commenting
    
    command argument argument1 …..

    Ejemplo de comandos + argumentos

    #Line blocks used for commenting
    
    command argument argument1 …..

    A continuación se muestra cómo se verá su flujo de trabajo.

    • Cree un Dockerfile y mencione las instrucciones para crear su imagen de Docker
    • Ejecute el comando docker build que creará una imagen de docker
    • Ahora que la imagen de la ventana acoplable está lista para usarse, use el comando de ejecución de la ventana acoplable para crear contenedores

    flujo de trabajo de dockerfile

    Comandos básicos

    DE - Define la imagen base para usar e iniciar el proceso de construcción.

    CORRER - Toma el comando y sus argumentos para ejecutarlo desde la imagen.

    CMD - Función similar a un comando RUN, pero se ejecuta solo después de que se crea una instancia del contenedor.

    PUNTO DE ENTRADA - Se dirige a su aplicación predeterminada en la imagen cuando se crea el contenedor.

    AÑADIR - Copia los archivos de origen a destino (dentro del contenedor).

    ENV - Establece variables de entorno.

    ¿Cómo crear una imagen de Docker con un Dockerfile?

    Primero, creemos un Dockerfile.

    [email protected]:~$ gedit Dockerfile

    Ponga los siguientes comandos / instrucciones y guárdelo.

    # Set the base image to Ubuntu
    FROM ubuntu
    
    # Update the repository sources list and install gnupg2
    RUN apt-get update && apt-get install -y gnupg2
    
    # Add the package verification key
    RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
    
    # Add MongoDB to the repository sources list
    RUN echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' > tee /etc/apt/sources.list.d/mongodb.list
    
    # Update the repository sources list
    RUN apt-get update
    
    # Install MongoDB package (.deb)
    RUN apt-get install -y mongodb
    
    # Create the default data directory
    RUN mkdir -p /data/db
    
    # Expose the default port
    EXPOSE 27017
    
    # Default port to execute the entrypoint (MongoDB)
    CMD ["--port 27017"]
    
    # Set default container command
    ENTRYPOINT usr/bin/mongodb

    En este Dockerfile, ubuntu se establece como imagen base. Luego se mencionan los comandos y argumentos necesarios para instalar MongoDB. El puerto 27017 está expuesto a MongoDB con el comando contenedor predeterminado como usr/bin/mongodb

    A continuación, lo ejecutaré para crear una imagen acoplable.

    Ejecutando un Dockerfile

    El siguiente comando creará una imagen de Docker llamada geekflare_mongodb después de una ejecución exitosa.

    [email protected]:~$ docker build -t geekflare_mongodb .
    
    Sending build context to Docker daemon  667.2MB
    
    Step 1/9 : FROM ubuntu
    
    latest: Pulling from library/ubuntu
    
    7413c47ba209: Pull complete
    
    0fe7e7cbb2e8: Pull complete
    
    1d425c982345: Pull complete
    
    344da5c95cec: Pull complete
    
    Digest: sha256:c303f19cfe9ee92badbbbd7567bc1ca47789f79303ddcef56f77687d4744cd7a
    
    Status: Downloaded newer image for ubuntu:latest
    
    ---> 3556258649b2
    
    Step 2/10 : RUN apt-get update && apt-get install -y gnupg2
    
    ---> Running in de3706328761
    
    Get:1 http://security.ubuntu.com/ubuntu bionic-security InRelease [88.7 kB]
    
    Get:2 http://archive.ubuntu.com/ubuntu bionic InRelease [242 kB]
    
    Fetched 16.9 MB in 38s (445 kB/s)
    
    Reading package lists...
    
    Reading package lists...
    
    Building dependency tree...
    
    Reading state information...
    
    Need to get 5187 kB of archives.
    
    After this operation, 15.8 MB of additional disk space will be used.
    
    Get:1 http://archive.ubuntu.com/ubuntu bionic/main amd64 readline-common all 7.0-3 [52.9 kB]
    
    Get:2 http://archive.ubuntu.com/ubuntu bionic/main amd64 libreadline7 amd64 7.0-3 [124 kB]
    
    Get:3 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libsqlite3-0 amd64 3.22.0-1ubuntu0.1 [497 kB]
    
    Get:4 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libssl1.1 amd64 1.1.1-1ubuntu2.1~18.04.4 [1300 kB]
    
    debconf: delaying package configuration, since apt-utils is not installed
    
    Fetched 5187 kB in 12s (416 kB/s)
    
    Selecting previously unselected package readline-common.
    
    (Reading database ... 4040 files and directories currently installed.)
    
    Preparing to unpack .../00-readline-common_7.0-3_all.deb ...
    
    Unpacking readline-common (7.0-3) ...
    
    Selecting previously unselected package libreadline7:amd64.
    
    Preparing to unpack .../01-libreadline7_7.0-3_amd64.deb ...
    
    Selecting previously unselected package dirmngr.
    
    Setting up libnpth0:amd64 (1.5-3) ...
    
    Setting up libksba8:amd64 (1.3.5-2) ...
    
    Setting up gnupg-l10n (2.2.4-1ubuntu1.2) ...
    
    Processing triggers for libc-bin (2.27-3ubuntu1) ...
    
    Removing intermediate container de3706328761
    
    ---> a32533894ed1
    
    Step 3/10 : RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
    
    ---> Running in 69c4dba38983
    
    Warning: apt-key output should not be parsed (stdout is not a terminal)
    
    Executing: /tmp/apt-key-gpghome.MuT5BDWwKZ/gpg.1.sh --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
    
    gpg: key 5F8F93707F0CEB10: public key "Totally Legit Signing Key <[email protected]>" imported
    
    gpg: key 9ECBEC467F0CEB10: 1 signature not checked due to a missing key
    
    gpg: key 9ECBEC467F0CEB10: public key "Richard Kreuter <[email protected]>" imported
    
    gpg: Total number processed: 2
    
    gpg:               imported: 2
    
    Removing intermediate container 69c4dba38983
    
    ---> cffbe06c1b50
    
    Step 4/10 : RUN echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' > tee /etc/apt/sources.list.d/mongodb.list
    
    ---> Running in 40630fd7b0a9
    
    Removing intermediate container 40630fd7b0a9
    
    ---> a1bd9d8d7e51
    
    Step 5/10 : RUN apt-get update
    
    ---> Running in 750717d9c0ea
    
    Hit:1 http://archive.ubuntu.com/ubuntu bionic InRelease
    
    Hit:2 http://archive.ubuntu.com/ubuntu bionic-updates InRelease
    
    Hit:3 http://security.ubuntu.com/ubuntu bionic-security InRelease
    
    Hit:4 http://archive.ubuntu.com/ubuntu bionic-backports InRelease
    
    Reading package lists...
    
    Removing intermediate container 750717d9c0ea
    
    ---> 397d6501db58
    
    Step 6/10 : RUN apt-get install -y mongodb
    
    ---> Running in 88609c005e73
    
    Reading package lists...
    
    Building dependency tree...
    
    Reading state information...
    
    The following NEW packages will be installed:
    
    libboost-filesystem1.65.1 libboost-iostreams1.65.1
    
    libboost-program-options1.65.1 libboost-system1.65.1 libgoogle-perftools4
    
    libpcap0.8 libpcrecpp0v5 libsnappy1v5 libstemmer0d libtcmalloc-minimal4
    
    libunwind8 libyaml-cpp0.5v5 mongo-tools mongodb mongodb-clients
    
    mongodb-server mongodb-server-core
    
    0 upgraded, 17 newly installed, 0 to remove and 0 not upgraded.
    
    Need to get 53.7 MB of archives.
    
    After this operation, 218 MB of additional disk space will be used.
    
    Get:1 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 mongodb-clients amd64 1:3.6.3-0ubuntu1.1 [20.2 MB]
    
    Get:2 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 mongodb-server-core amd64 1:3.6.3-0ubuntu1.1 [20.3 MB]
    
    Get:3 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 mongodb-server all 1:3.6.3-0ubuntu1.1 [12.6 kB]
    
    Get:4 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 mongodb amd64 1:3.6.3-0ubuntu1.1 [9968 B]
    
    Fetched 53.7 MB in 10s (5485 kB/s)
    
    Selecting previously unselected package libpcap0.8:amd64.
    
    (Reading database ... 4390 files and directories currently installed.)
    
    Selecting previously unselected package mongodb-clients.
    
    Preparing to unpack .../13-mongodb-clients_1%3a3.6.3-0ubuntu1.1_amd64.deb ...
    
    Unpacking mongodb-clients (1:3.6.3-0ubuntu1.1) ...
    
    Selecting previously unselected package mongodb-server-core.
    
    Preparing to unpack .../14-mongodb-server-core_1%3a3.6.3-0ubuntu1.1_amd64.deb ...
    
    Unpacking mongodb-server-core (1:3.6.3-0ubuntu1.1) ...
    
    Selecting previously unselected package mongodb-server.
    
    Preparing to unpack .../15-mongodb-server_1%3a3.6.3-0ubuntu1.1_all.deb ...
    
    Unpacking mongodb-server (1:3.6.3-0ubuntu1.1) ...
    
    Selecting previously unselected package mongodb.
    
    Preparing to unpack .../16-mongodb_1%3a3.6.3-0ubuntu1.1_amd64.deb ...
    
    Unpacking mongodb (1:3.6.3-0ubuntu1.1) ...
    
    Setting up mongodb-server-core (1:3.6.3-0ubuntu1.1) ...
    
    Setting up mongo-tools (3.6.3-0ubuntu1) ...
    
    Setting up mongodb-clients (1:3.6.3-0ubuntu1.1) ...
    
    Setting up mongodb-server (1:3.6.3-0ubuntu1.1) ...
    
    invoke-rc.d: could not determine current runlevel
    
    invoke-rc.d: policy-rc.d denied execution of start.
    
    Setting up mongodb (1:3.6.3-0ubuntu1.1) ...
    
    Processing triggers for libc-bin (2.27-3ubuntu1) ...
    
    Removing intermediate container 88609c005e73
    
    ---> d9c072cb1f84
    
    Step 7/10 : RUN mkdir -p /data/db
    
    ---> Running in f817778f69ab
    
    Removing intermediate container f817778f69ab
    
    ---> a3fbdb3def5c
    
    Step 8/10 : EXPOSE 27017
    
    ---> Running in 8d070e2a1e07
    
    Removing intermediate container 8d070e2a1e07
    
    ---> f770776a538c
    
    Step 9/10 : CMD ["--port 27017"]
    
    ---> Running in ab612410df77
    
    Removing intermediate container ab612410df77
    
    ---> e5830b80934f
    
    Step 10/10 : ENTRYPOINT usr/bin/mongod
    
    ---> Running in 95f574727aab
    
    Removing intermediate container 95f574727aab
    
    ---> 095d17727ca0
    
    Successfully built 095d17727ca0
    
    Successfully tagged geekflare_mongodb:latest

    Comprobemos si la imagen de la ventana acoplable se creó con el nombre geekflare_mongodb.

    [email protected]:~$ docker images
    
    REPOSITORY                 TAG                 IMAGE ID            CREATED             SIZE
    
    geekflare_mongodb          latest              095d17727ca0        3 minutes ago       325MB
    
    ubuntu                     latest              3556258649b2        4 days ago          64.2MB
    
    mean_express               latest              35dcb3df9806        6 days ago          923MB
    
    mean_angular               latest              9f8d61db600c        6 days ago          1.29GB

    Ejecute la imagen de la ventana acoplable geekflare_mongodb dentro de un contenedor mongo_container.

    [email protected]:~$ docker run --name mongo_container -i -t geekflare_mongodb
    
    2019-07-27T19:38:23.734+0000 I CONTROL  [initandlisten] MongoDB starting : pid=6 port=27017 dbpath=/data/db 64-bit host=b0095c1e5536
    
    2019-07-27T19:38:23.735+0000 I CONTROL  [initandlisten] db version v3.6.3
    
    2019-07-27T19:38:23.735+0000 I CONTROL  [initandlisten] git version: 9586e557d54ef70f9ca4b43c26892cd55257e1a5
    
    2019-07-27T19:38:23.736+0000 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.1.1  11 Sep 2018
    
    2019-07-27T19:38:23.739+0000 I CONTROL  [initandlisten] allocator: tcmalloc
    
    2019-07-27T19:38:23.739+0000 I CONTROL  [initandlisten] modules: none
    
    2019-07-27T19:38:23.739+0000 I CONTROL  [initandlisten] build environment:
    
    2019-07-27T19:38:23.739+0000 I CONTROL  [initandlisten]     distarch: x86_64
    
    2019-07-27T19:38:23.739+0000 I CONTROL  [initandlisten]     target_arch: x86_64
    
    2019-07-27T19:38:23.739+0000 I CONTROL  [initandlisten] options: {}
    
    2019-07-27T19:38:23.745+0000 I STORAGE  [initandlisten] wiredtiger_open config: create,cache_size=2038M,session_max=20000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),statistics_log=(wait=0),verbose=(recovery_progress),
    
    2019-07-27T19:38:24.733+0000 I CONTROL  [initandlisten]
    
    2019-07-27T19:38:24.734+0000 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
    
    2019-07-27T19:38:24.735+0000 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
    
    2019-07-27T19:38:24.736+0000 I CONTROL  [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
    
    2019-07-27T19:38:24.736+0000 I CONTROL  [initandlisten]
    
    2019-07-27T19:38:24.736+0000 I CONTROL  [initandlisten] ** WARNING: This server is bound to localhost.
    
    2019-07-27T19:38:24.737+0000 I CONTROL  [initandlisten] **          Remote systems will be unable to connect to this server.
    
    2019-07-27T19:38:24.737+0000 I CONTROL  [initandlisten] **          Start the server with --bind_ip <address> to specify which IP
    
    2019-07-27T19:38:24.737+0000 I CONTROL  [initandlisten] **          addresses it should serve responses from, or with --bind_ip_all to
    
    2019-07-27T19:38:24.737+0000 I CONTROL  [initandlisten] **          bind to all interfaces. If this behavior is desired, start the
    
    2019-07-27T19:38:24.738+0000 I CONTROL  [initandlisten] **          server with --bind_ip 127.0.0.1 to disable this warning.
    
    2019-07-27T19:38:24.738+0000 I CONTROL  [initandlisten]
    
    2019-07-27T19:38:24.739+0000 I STORAGE  [initandlisten] createCollection: admin.system.version with provided UUID: 4b8b509d-633a-46c1-a302-cb8c82b0d5d3
    
    2019-07-27T19:38:24.788+0000 I COMMAND  [initandlisten] setting featureCompatibilityVersion to 3.6
    
    2019-07-27T19:38:24.818+0000 I STORAGE  [initandlisten] createCollection: local.startup_log with generated UUID: 6c1c0366-4b1b-4b92-9fcd-d18acc126072
    
    2019-07-27T19:38:24.862+0000 I FTDC     [initandlisten] Initializing full-time diagnostic data capture with directory '/data/db/diagnostic.data'
    
    2019-07-27T19:38:24.866+0000 I NETWORK  [initandlisten] waiting for connections on port 27017

    Abra una nueva terminal y verifique si mongo_container se está ejecutando.

    [email protected]:~$ docker ps
    
    CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
    
    b0095c1e5536        geekflare_mongodb   "/bin/sh -c usr/bin/…"   35 seconds ago      Up 33 seconds       27017/tcp           mongo_container

    Como puede ver, el contenedor creado a partir de geekflare_mongodb la imagen está en funcionamiento.

    Espero que esto le dé una idea sobre dockerfile y sus beneficios. También puede consultar esta documentación en Mejores prácticas de Dockerfile para obtener más información.