¿Qué es un Dockerfile y cómo usarlo?
Un Dockerfile es la receta para crear una imagen de Docker.
Este es el flujo de trabajo: primero crea un Dockefile, luego crea una imagen de Docker usandodocker build
, y finalmente ejecuta un contenedor desde la imagen.
Un Dockerfile es un archivo de texto con instrucciones sobre cómo crear una imagen.
Esas instrucciones forman parte de un lenguaje de configuración, que incluye palabras clave comoFROM
,LABEL
,RUN
,COPY
,ENTRYPOINT
,CMD
,EXPOSE
,ENV
y más.
Creemos nuestro primer Dockerfile:
Digamos que tiene una carpeta con una aplicación Node.js simple compuesta por unapp.js
, apackage.json
archivo que enumera un par de dependencias que necesita instalar antes de ejecutar la aplicación, ypackage-lock.json
.
Dentro de él, cree un archivo de texto sin formato llamadoDockerfile
, sin extensión, con este contenido:
FROM node:14
WORKDIR /usr/src/app
COPY package*.json app.js ./
RUN npm install
EXPOSE 3000
CMD ["node", "app.js"]
NOTE: use double quotes in the CMD
line. Single quotes will result in an error.
In the first line we say which image we want to start from. This will be our base image. In this case it will take the official Node.js image, based on Alpine Linux, using Node 14. When creating a container from the Dockerfile, Docker will get that image from Docker Hub.
Next we set the working directory to /usr/src/app
, which means all our commands will be run in that folder until we change it again. That’s a folder we know already exists in the Node image.
We copy the package.json
, package-lock.json
(using the *
wildcard) and app.js
files that are present in the current folder, into the working directory.
We run npm install
to install the packages listed in the package.json
file.
Then we expose port 3000 to the outside, since that’s what our app runs on. A container is 100% isolated from the network unless you expose one of its ports using the EXPOSE
command. We’ll later see how we can map ports on our computer to ports in a Docker container.
Finally we run node app.js
to start the app.
This is a Dockerfile, and we’ll soon see how to actually create a container from it.
More docker tutorials:
- Introduction to Docker
- Introduction to Docker Images
- Introduction to Docker Containers
- Dockerfiles
- Installing Docker on macOS
- First steps with Docker after the installation
- Using Docker Desktop to manage a Container
- Create a simple Node.js Hello World Docker Container from scratch
- What to do if a Docker container immediately exits
- Working with Docker Containers from the command line
- Working with Docker Images from the command line
- Sharing Docker Images on Docker Hub
- How to access files outside a Docker container
- How to commit changes to a Docker image
- Updating a deployed container based on a Docker image