Skip to content

Manage Docker Containers Volume and Environment

Volume

Creating a volume

docker container run --name demo \
    alpine /bin/sh -c 'echo "This is a test" > sample.txt'

docker container diff demo

docker volume create sample
docker volume inspect sample
[
    {
        "CreatedAt": "2021-09-23T14:46:59Z",
        "Driver": "local",
        "Labels": {},
        "Mountpoint": "/var/lib/docker/volumes/sample/_data",
        "Name": "sample",
        "Options": {},
        "Scope": "local"
    }
]

Mounting a volume

docker container run --name test -it \
    -v sample:/data \
    alpine /bin/sh

cd /data / && echo "hello world" > data.txt && exit

ls /var/lib/docker/volumes/sample/_data

Removing volumes

docker volume rm sample

## emove all running containers
docker container rm -f $(docker container ls -aq)

Sharing data between containers

docker container run -it --name writer \
    -v shared-data:/data \
    alpine /bin/sh

docker container run -it --name reader \
    -v shared-data:/app/data:ro \
    ubuntu:18.04 /bin/bash

Using host volumes

mkdir /opt/src
docker container run --rm -it \
    -v /opt/src:/app/src \
    alpine:latest /bin/sh

Defining volumes in images

VOLUME /app/data
VOLUME /app/data, /app/profiles, /app/config
VOLUME ["/app/data", "/app/profiles", "/app/config"]

Env

Defining environment variables for containers

docker container run --rm -it \
    --env LOG_DIR=/var/log/my-log \
    alpine /bin/sh
export && exit

env.conf

LOG_DIR=/var/log/my-log
MAX_LOG_FILES=5
MAX_LOG_SIZE=1G
docker container run --rm -it \
    --env-file ./env.conf \
    alpine sh -c "export"

Defining environment variables in container images

Dockerfile

FROM alpine:latest
ENV LOG_DIR=/var/log/my-log
ENV  MAX_LOG_FILES=5
ENV MAX_LOG_SIZE=1G
docker image build -t my-alpine .
docker container run --rm -it \
    my-alpine sh -c "export | grep LOG"

Environment variables at build time

Dockerfile

ARG BASE_IMAGE_VERSION=12.7-stretch FROM node:${BASE_IMAGE_VERSION} WORKDIR /app
COPY packages.json .
RUN npm install
COPY . .
CMD npm start
docker image build \
    --build-arg BASE_IMAGE_VERSION=12.7-alpine \
    -t my-node-app-test .

Disclaimer
  1. License under CC BY-NC 4.0
  2. Copyright issue feedback me#imzye.me, replace # with @
  3. Not all the commands and scripts are tested in production environment, use at your own risk
  4. No privacy information is collected here
Try my iOS App