🚢

Docker

Created
TypePlatform
LanguageShell
Last Edit

Basics

Platform for building, running and shipping applications.

Docker helps package the required versions of dependencies for an app in an isolated environment called container.

It helps developers to remove an app and all of its dependencies in one go.

Architecture

Container uses underlying OS kernel to run.

Linux: Linux containers can be run.

Windows: Both Windows & Linux containers can be run.

Mac: Requires light weigh Linux VM to run containers.

Development Workflow

Add a docker file to an application to convert application to an image.

Image

It will contain everything an application needs to run.

Container

Docker uses created image to start a container (or process) in an isolated environment.

Docker Hub

Similar to Github for Git.

Once application image is on Docker Hub, we can pull to any machine running docker to run the application

Ubuntu VPS

How to Install and Set Up Docker on Ubuntu
Docker is one of the most convenient tools for deploying an application. Improve your project and learn how to install Docker on Ubuntu.
https://www.hostinger.com/tutorials/how-to-install-docker-on-ubuntu

Images Available

Explore Docker's Container Image Repository | Docker Hub

Dockerfile - Best Practices Template

Dockerfiles

Node

error: Environment variable not found: DATABASE_URL. · prisma prisma · Discussion #17731
Bug description Hello. I'm struggling with connecting to a database running in the docker container alongside my main app (nestjs+prisma). I'm getting the following error: #0 9.627 Prisma s...
https://github.com/prisma/prisma/discussions/17731

Index.js

FROM node:alpine
WORKDIR /app
COPY . /app
CMD node .
# syntax=docker/dockerfile:1

# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Dockerfile reference guide at
# https://docs.docker.com/go/dockerfile-reference/

# Want to help us make this template better? Share your feedback here: https://forms.gle/ybq9Krt8jtBL3iCk7

ARG NODE_VERSION=22.11.0

FROM node:${NODE_VERSION}-alpine

# Use production node environment by default.
ENV NODE_ENV production


WORKDIR /usr/src/app

# Download dependencies as a separate step to take advantage of Docker's caching.
# Leverage a cache mount to /root/.npm to speed up subsequent builds.
# Leverage a bind mounts to package.json and package-lock.json to avoid having to copy them into
# into this layer.
RUN --mount=type=bind,source=package.json,target=package.json \
    --mount=type=bind,source=package-lock.json,target=package-lock.json \
    --mount=type=cache,target=/root/.npm \
    npm ci --omit=dev

# Run the application as a non-root user.
USER node

# Copy the rest of the source files into the image.
COPY . .

# Expose the port that the application listens on.
EXPOSE 8001

# Run the application.
CMD npm run api-dev

General dockerfile

FROM node:alpine
WORKDIR /usr/app
COPY package.json .
RUN npm install --quiet
COPY . .

Php with apache

FROM php:7.2-apache
COPY src/ /var/www/html/

Node on Ubuntu

FROM ubuntu:latest

ENV APP_HOME=/app
ENV NVM_DIR=$APP_HOMEe/.nvm

ARG NODE_VERSION=14.17.3

WORKDIR $APP_HOME

COPY . $APP_HOME

RUN apt-get update \
    && apt-get install -y \
    curl \
    zip \
    unzip \
    # && curl -fsSL https://deb.nodesource.com/setup_14.x | bash - \
    # && apt-get install -y nodejs
    # NodeJS
    && mkdir -p ${NVM_DIR} \
    && curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.5/install.sh | bash \
    && . ${NVM_DIR}/nvm.sh \
    && nvm install ${NODE_VERSION} \
    && nvm use v${NODE_VERSION} \
    && npm install -g yarn \
    && nvm alias default v${NODE_VERSION} \
    && rm -rf ${NVM_DIR}/.cache \
    && echo 'export NVM_DIR="/app/.nvm"' >>/app/.bashrc \
    && echo '[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm' >>/app/.bashrc \
    && echo '[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion' >>/app/.bashrc \
    && npm config set engine-strict true \
    && npm install

React

FROM node:latest
WORKDIR /app
COPY package.json ./
RUN npm install
COPY . .
CMD ["npm", "start"]

.dockerignore

node_modules
Dockerfile
.git

Django

awesome-compose/official-documentation-samples/django at master · docker/awesome-compose
This quick-start guide demonstrates how to use Docker Compose to set up and run a simple Django/PostgreSQL app. Before starting, install Compose. For this project, you need to create a Dockerfile, a Python dependencies file, and a docker-compose.yml file. (You can use either a .yml or .yaml extension for this file.)
https://github.com/docker/awesome-compose/tree/master/official-documentation-samples/django

Java

RUN apt-get install -y openjdk-8-jdk
RUN apt-get install -y software-properties-common

RUN whereis java
RUN ls /usr/lib/jvm
ENV JAVA_HOME="/usr/lib/jvm/java-8-openjdk-arm64"

# Verify the installation and environment variable
RUN echo "JAVA_HOME is set to $JAVA_HOME" && \
    echo "Java version:" && \
    $JAVA_HOME/bin/java -version

Keep Alive

CMD ["tail", "-f", "/dev/null"]

Build

Run command inside working directory with Dockerfile

docker build -t image_name:image_tag .

Run a specific file for build

docker build -t <image-name>:<tag> -f <Dockerfile-name> <path-to-Dockerfile-directory>

Example:

docker build -t clock:service-heroku -f Dockerfile.clock .

Clean Up Storage

If required

docker system prune

Run Container

React

docker run --name container_name -d -p 3000:3000 image_name:image_tag
💡
goto localhost:3000 to view page

With Hot-Reload

docker run -it --rm -v ${PWD}:/app -v /app/node_modules -e CHOKIDAR_USEPOLLING=true -p 3001:3000 image_name:image_tag

AWS

docker run --rm -it amazon/aws-cli command

Docker List

List All Containers

docker container ls -a

Running Containers

docker ps

Docker Start

docker start containerid

Docker Stop

docker stop containerid

Running web server without Dockerfile

Running php and apache

Run this command in terminal inside a repository

docker run -d -p 80:80 --name my-apache-php-app -v "$PWD":/var/www/html php:7.2-apache
💡
goto localhost:80 to view page

Running multiple servers with port mapping

Networking in Compose
How Docker Compose sets up networking between containers
https://docs.docker.com/compose/networking/

local port ⇒ container port

⚠️ Container port is always 80 unless changed in httpd.conf

docker run -d -p 8000:80 --name my-apache-php-app-2 -v "$PWD":/var/www/html php:7.2-apache
💡
goto localhost:8000 to view page

Docker Compose

No Cache

--no-cache
docker compose -f docker-compose.dev.yml build --no-cache

docker-compose.yml

NodeJS

version: "2"
services:
  web:
    build: .
    command: node .
    volumes:
      - .:/usr/app/
      - /usr/app/node_modules
    ports:
      - "8001:3000"
# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Docker Compose reference guide at
# https://docs.docker.com/go/compose-spec-reference/

# Here the instructions define your application as a service called "server".
# This service is built from the Dockerfile in the current directory.
# You can add other services your application may depend on here, such as a
# database or a cache. For examples, see the Awesome Compose repository:
# https://github.com/docker/awesome-compose
services:
  server:
    build:
      context: .
    environment:
      NODE_ENV: production
    ports:
      - 8001:8001

# The commented out section below is an example of how to define a PostgreSQL
# database that your application can use. `depends_on` tells Docker Compose to
# start the database before your application. The `db-data` volume persists the
# database data between container restarts. The `db-password` secret is used
# to set the database password. You must create `db/password.txt` and add
# a password of your choosing to it before running `docker-compose up`.
#     depends_on:
#       db:
#         condition: service_healthy
#   db:
#     image: postgres
#     restart: always
#     user: postgres
#     secrets:
#       - db-password
#     volumes:
#       - db-data:/var/lib/postgresql/data
#     environment:
#       - POSTGRES_DB=example
#       - POSTGRES_PASSWORD_FILE=/run/secrets/db-password
#     expose:
#       - 5432
#     healthcheck:
#       test: [ "CMD", "pg_isready" ]
#       interval: 10s
#       timeout: 5s
#       retries: 5
# volumes:
#   db-data:
# secrets:
#   db-password:
#     file: db/password.txt

Django

How to Build a Django and Gunicorn Application with Docker | DigitalOcean
Interested in Django but not sure where to start with Docker? This tutorial will walk you through first steps: modifying a sample Django application to work …
https://www.digitalocean.com/community/tutorials/how-to-build-a-django-and-gunicorn-application-with-docker

Redis, Mongo, Celery

There are going to be 5 services in total:

Add MongoDB and PostgreSQL in Django using Docker
Originally published in The Pylot In this post, you'll learn how to integrate multiple databases...
https://dev.to/thepylot/add-mongodb-and-postgresql-in-django-using-docker-55j6

Execute

Run this command in the current directory with docker-compose.yml

docker compose up

Command to specify docker compose file

docker compose -f docker-compose-local.yml up

Build

docker-compose --build
OR
docker compose -f docker-compose-local.yml up --build

Run

docker-compose up -d

Set Memory For Build

docker run -m 4g -it my-docker-image

Shutdown

docker compose down

Shutdown with removing volumes

docker compose down -v

Environment Variables

Ways to set environment variables with Compose
How to set, use, and manage environment variables with Compose
https://docs.docker.com/compose/environment-variables/set-environment-variables/

Log Env Variables in Container

docker-compose exec db env
docker compose -f docker-compose.dev.yml exec api env 

Managing Multiple Environments

Extend your Compose file
How to use Docker Compose's extends keyword to share configuration between files and projects
https://docs.docker.com/compose/multiple-compose-files/extends/

Docker Inspect

Get all details about running container, including Host IP and port.

docker inspect postgresql

Docker Bash

docker exec -it <container-name> sh
docker exec -it <container_name_or_id> bash

Logs

docker-compose logs -f
docker logs --tail 100 my-container

Docker Commands Execute

Django

Migrate

docker-compose exec web python manage.py migrate

Create Super User

docker-compose exec web python manage.py createsuperuser

Docker Network

Postgres Container

Compose with Health Check

postgres:
    image: postgres:13
    ports:
      - 5432:5432
    environment:
      POSTGRES_USER: airflow
      POSTGRES_PASSWORD: airflow
      POSTGRES_DB: airflow
    volumes:
      - postgres-db-volume:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD", "pg_isready", "-U", "airflow"]
      interval: 5s
      retries: 5
    restart: always

Data Initialisation

Initializing a PostgreSQL Database with a Dataset using Docker Compose: A Step-by-step Guide
Deploying and initializing a PostgreSQL database doesn’t always have to be a manual process. With Docker Compose, we can not only automate…
https://medium.com/@asuarezaceves/initializing-a-postgresql-database-with-a-dataset-using-docker-compose-a-step-by-step-guide-3feebd5b1545

Shell

docker ps
docker exec -it <container_name_or_id> bash

Docker Watch

Use watch to automatically update and preview your running Compose services as you edit and save your code.

Use Compose Watch
Use File watch to automatically update running services as you work
https://docs.docker.com/compose/file-watch/

Docker Permissions

 sudo usermod -a -G docker local
newgrp docker is used to change your users group ID to docker (to avoid having to log out and log in again)