Introduction
A Dockerfile is a plain-text document describing how to build a Docker image. The Dockerfile contains all the commands a user could call on the command line to assemble an image. Using docker build
users can create an automated build that executes several command-line instructions in succession.
Example DockerFile
This is an example of a Dockerfile for a Node.js app. It uses the Alpine Linux image as a base, installs Node.js and npm, copies the app code into the image, installs the app dependencies, exposes port 8080, and sets the entrypoint to run the app.
Essential Directives
FROM
The FROM
directive specifies the base image to use for the build. It can be any image available on Docker Hub or a custom image. The FROM
directive must be the first instruction in the Dockerfile.
LABEL
The LABEL
directive adds metadata to an image. A label is a key-value pair. It is used to add information about the image, such as the maintainer’s email address.
RUN
The RUN
directive executes a command in a new layer on top of the current image and commits the results. The resulting image is used for the next step in the Dockerfile. The RUN
directive can be used to install packages, update the system, or run any command that is needed to set up the image.
COPY
The COPY
directive copies files or directories from the host system to the image. It takes two arguments: a source and a destination. The source can be a file or a directory on the host system, and the destination is the path in the image where the file or directory will be copied.
WORKDIR
The WORKDIR
directive sets the working directory for any RUN
, CMD
, ENTRYPOINT
, COPY
, and ADD
instructions that follow it in the Dockerfile. It can be used to avoid repeating the path in multiple instructions.
EXPOSE
The EXPOSE
directive informs Docker that the container listens on the specified network ports at runtime. It does not actually publish the port. It is used to document which ports are intended to be published.
ENTRYPOINT
The ENTRYPOINT
directive specifies the command that will be run when the container starts. It can be overridden by passing a command to docker run
. The ENTRYPOINT
can be a shell script, a binary, or a shell command.
Essential Commands
Build
Build an image from a Dockerfile locally. Be sure to perform this command from within the directory containing the app code and Dockerfile. The --tag
flag is used to give the image a name and a tag. It can then be run using the docker run
command or via Docker Compose.
Example
Download Repo
This is a simple web app that displays a message in a web page. It’s written in Node.js and uses the Express.js framework.
Build
Build the image using the Dockerfile in the current directory with the tag test
.
Run
Run the container in detached mode, name it web1
, and map port 8080 on the host to port 8080 in the container.
Access
it will be available at http://localhost:8080