Skip to main content

Parts of Dockerfile

# Create image based on the official Node image from dockerhub
FROM node:lts-buster

# Create app directory
WORKDIR /usr/src/app

# Copy dependency definitions
# copies package.json from project to workdir
COPY package.json .

COPY package-lock.json .

# Install dependecies same as npm install
RUN npm ci

# Get all the code needed to run the app
COPY . .

# Expose the port the app runs in
EXPOSE 3000

# Serve the app
CMD ["npm", "start"]

From​

  • The OS/framework used. Common is alpine, debian, ubuntu
FROM UBUNTU:18:04
FROM node:latest
FROM node:14

WORKDIR​

  • The WORKDIR instruction sets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow it in the Dockerfile.
  • If the WORKDIR doesn’t exist, it will be created even if it’s not used in any subsequent Dockerfile instruction.
  • It is recommended to use workdir as it makes the dockerfile more readable
WORKDIR /app
FROM nginx:latest # Extends nginx so everything included in that image is included here

WORKDIR /usr/share/nginx/html

COPY index.html index.html #directly copies the file inside workdir(/usr/share/nginx/html)

ENV​

  • Environment variables
ENV NODE_ENV = production

RUN​

  • Run commands/shell scripts inside the container, etc
  • To run commands inside the containers, such as to install dependencies and updates
RUN npm install
RUN apt-get install -y node

EXPOSE​

  • Ports to expose
  • The EXPOSE instruction does not actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container, about which ports are intended to be published.
    • It simply is a message for the developer on which port to use, but also the developer can use whichever port it want at runtime.
EXPOSE 8080

Expose Multiple Port​

EXPOSE 8080 5055 5005

CMD​

  • The Command that runs when you 'docker run' a new image
CMD ["node", "app.js"]

Multiple CMD Can Be Used​

CMD service sshd start && /opt/mq/sbin/rabbitmq-server start

COPY​

  • Copies files from host to container
COPY package*.json . #copy package to container
COPY . . #copy everything to container

Build the Docker into Image​

Examples​

More examples here

Nodejs Dockerfile​

FROM node:12.18.1

ENV NODE_ENV=production

WORKDIR /app

COPY ["package.json", "package-lock.json*", "./"]

RUN npm install --production

COPY . .

CMD [ "node", "server.js" ]

it is a best practice to define a .dockerignore file for your images

#.dockerignore
node_modules

Spring Boot Dockerfile​

FROM openjdk:16-alpine3.13

WORKDIR /app

COPY .mvn/ .mvn
COPY mvnw pom.xml ./
RUN ./mvnw dependency:go-offline

COPY src ./src

CMD ["./mvnw", "spring-boot:run"]