Manage Docker Containers Volume and Environment
Docker volume is a way to store and manage persistent data in Docker containers. A Docker volume is a directory on the host system that is mounted into a container. Data stored in a Docker volume persists even after the container is deleted. Docker volumes are useful for storing data that needs to be shared between multiple containers, such as databases or configuration files.
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 .
Back to Table of Contents
Disclaimer
- License under
CC BY-NC 4.0
- Copyright issue feedback
me#imzye.com
, replace # with @ - Not all the commands and scripts are tested in production environment, use at your own risk
- No personal information is collected.
Feedback