What Dockerfile is and common commands
Docker can build images automatically by reading the instructions from a Dockerfile. A Dockerfile is a text document that 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.
- FROM - The▶
FROMinstruction initializes a new build stage and sets the Base Image for subsequent instructions. As such, a valid Dockerfile must start with a
FROMinstruction. The image can be any valid image
- ENV - The▶
ENVinstruction sets the environment variable
- RUN - The▶
RUNinstruction will 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
- LABEL - The▶
LABELinstruction adds metadata to an image. A
LABELis a key-value pair. To include spaces within a
LABELvalue, use quotes and backslashes as you would in command-line parsing.
- EXPOSE - The▶
EXPOSEinstruction informs Docker that the container listens on the specified network ports at runtime. You can specify whether the port listens on TCP or UDP, and the default is TCP if the protocol is not specified.
- COPY - The▶
COPYinstruction copies new files or directories from
<src>and adds them to the filesystem of the container at the path
- WORKDIR - The▶
WORKDIRinstruction sets the working directory for any
ADDinstructions that follow it in the
Dockerfile. If the
WORKDIRdoesn’t exist, it will be created even if it’s not used in any subsequent
- CMD - Specifies the command to run when container starts. If you would like your container to run the same executable every time, then you should consider using▶
ENTRYPOINTin combination with
Order of instructions in Dockerfile matters, as all commands on Dockerfile as executed sequentially, and some instruction resulting in its own layer, increasing image size as a result. Instructions that are changing more frequently should be placed closer to the bottom, and instructions that don't change or change less frequently, should be placed higher in the Dockerfile. When one of the instruction changes,
COPYfor instance, all subsequent instructions must be re-run.
# From Node 10, Alpine 3.9 OS.
# Current directory.
# Install NPM packages
COPY ./package.json ./
RUN npm install
# Copy app files
COPY ./*.js ./
# Run app
CMD ["npm", "start"]