A Dockerfile is a text file that contains a set of instructions for building a Docker image. The instructions are written in a specific format and order, which defines the steps needed to create the image. Here is the basic structure of a Dockerfile:
Base image: The first line of a Dockerfile specifies the base image to use for the new image. The base image provides the operating system and any pre-installed software needed to run the application.
FROM <image>:<tag>
For example, to use the official Node.js 14-alpine image as the base image, you would write:
FROM node:14-alpine
Environment variables: You can define environment variables in a Dockerfile that can be used to configure the image at runtime.
ENV <key> <value>
For example, to set the environment variable NODE_ENV to production, you would write:
ENV NODE_ENV production
Working directory: You can specify the working directory for the new image, which defines the location where the application code will be stored.
WORKDIR /app
Copy files: You can copy files from the host system to the image using the COPY instruction.
COPY <src> <dest>
For example, to copy the package.json and package-lock.json files to the working directory in the image, you would write:
COPY package*.json ./
Run commands: You can run commands in the image using the RUN instruction.
RUN <command>
For example, to install the dependencies for a Node.js application, you would write:
RUN npm install
Expose ports: You can specify which ports should be exposed by the new image.
EXPOSE <port>
For example, to expose port 3000, you would write:
EXPOSE 3000
Start command: You can specify the command to run when the container is started using the CMD instruction.
CMD ["<command>", "<arg1>", "<arg2>", ...]
For example, to start a Node.js application, you would write:
CMD ["npm", "start"]
Here is an example of a simple Dockerfile for a Node.js web application:
FROM node:14-alpine
ENV NODE_ENV production
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
This Dockerfile specifies that the image should be based on the official Node.js 14-alpine image, sets the environment variable NODE_ENV to production, installs the dependencies needed to run the application, copies the application code to the working directory, exposes port 3000 for the application to run on, and starts the application with the npm start command.