Skip to main content

One Page | Docker Study Guide

ENV and ARG

ENV and ARG values specified in Dockerfile are a mechanism to pass default env vars to running docker images. Think of it as an alternative to .env in Node.js. Executing os env variable take priority while running and can be used as an overriding mechanism.

Refer: https://docs.docker.com/engine/reference/builder/#env

Simple Node.js Dockerfile

FROM node:lts-alpine3.17

RUN apk update && \
apk upgrade && \
apk add --no-cache bash git openssh

RUN mkdir /app
WORKDIR /app
COPY package.json .
RUN npm install

COPY . .

ENV SERVER_PORT=3030

EXPOSE 3030

CMD ["npm", "start"]

To run

#!/usr/bin/env bash

# run in foreground
docker run --init -p 8000:8000 -it wapp-erealms-cli-server

# run detached
docker run -d -p 8000:8000 wapp-erealms-cli-server

# cleanup after run
# https://docs.docker.com/engine/reference/run/#clean-up---rm
docker run --rm -v /foo -v awesome:/bar busybox top

Sample bash script to run detached

#!/usr/bin/env bash
docker run -d -p 8000:8000 wapp-erealms-cli-server

Muti Stage Dockerfile example

Multistage Docker Build

# ----Multistage build [1] build [2] Copy -----
FROM node:lts-alpine3.14 as build
RUN apk update && \
apk upgrade && \
apk add --no-cache bash git openssh
RUN mkdir /app
WORKDIR /app
COPY package.json .
# installs npm,yarn
RUN npm install -g --force npm@latest yarn@latest
# creates node modules
RUN yarn install
# copy source files
COPY . .
# run build for production
RUN yarn build

# --------STAGE 2 - Server via NGINX-------
# nginx state for serving content
FROM nginx:alpine
# Set working directory to nginx asset directory
WORKDIR /usr/share/nginx/html
# Remove default nginx static assets
RUN rm -rf ./*
# Copy static assets over
COPY --from=build /app/build .
# Containers run nginx with global directives and daemon off
ENTRYPOINT ["nginx", "-g", "daemon off;"]

Building a Docker image

Sample bash script

#!/usr/bin/env bash
docker build -t wapp-erealms-cli-server .

Pushing a Docker image to a registry

Google Cloud Artifact Registry

Check out -> artifact-registry.md