docker save / docker load
イメージのバックアップ、他ホストへの移行(docker load)
docker save: Produces a tarred repository to the standard output stream.
Contains all parent layers, and all tags + versions, or specified `repo:tag`, for
each argument provided.
$ docker save -o <path for generated tar file> <image name>
$ docker load -i <path to image tar file>
docker
Dockerイメージを確認しタグ付きでtarファイルで出力
ex)
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
mariadb latest xxxxxxxxxxxxx 4 months ago 414MB
$ docker save -o ./mariadb.tar mariadb:latest
移行先システムへ上記tarファイルをコピーしてロード
$ docker load -i mariadb.tar
ホストマシンの全イメージを保存する場合
docker
全イメージファイルを1つのtarファイルで保存
$ docker save $(docker images -q) -o /path/to/save/mydockersimages.tar
各イメージのタグは別ファイルで保存
$ docker images | sed '1d' | awk '{print $1 " " $2 " " $3}' > mydockersimages.list
他のホストマシンで読み込む場合
$ docker load -i /path/to/save/mydockersimages.tar
$ while read REPOSITORY TAG IMAGE_ID
do
echo "== Tagging $REPOSITORY $TAG $IMAGE_ID =="
docker tag "$IMAGE_ID" "$REPOSITORY:$TAG"
done < mydockersimages.list
Docker-composeファイルによるタイムゾーンの指定
タイムゾーンデータを含んでいるDockerイメージファイルでローカルタイムを指定する場合
environment:
- TZ=Asia/Tokyo
Alpine-Linux をベースとしたイメージファイルなど、タイムゾーンデータが予めインストールされていない場合、別途Dockerfile を作成し、インストールコマンドを記述する必要が有ります。
Docker-composeファイルによる複数の.envファイルの指定 env_file
Docker-composeファイル内で複数のサービス(コンテナ)を起動する際に、デフォルトで読み込まれる.envファイルとは別に、任意のサービス起動向けに、別途用意した環境変数を追加する場合に利用します。
env_file:
- ./common.env
- ./apps/web.env
- /opt/runtime_opts.env
environmentセクションで指定した環境変数は全て、ここで指定した環境変数に上書きされます。
Compose file: extra_hosts
コンテナ内で名前解決に問題(主に接続エラー)が生じた場合、コンテナ内におけるドメイン名とIPアドレスのマッピングを追加します。
Find a quick reference for Docker Compose version 3, including Docker Engine compatibility, memory limitations, and more.
extra_hosts:
- "somehost:162.242.195.82"
- "otherhost:50.31.209.229"
コンテナ内の /etc/hosts にドメイン名の対応IPアドレスが追加されます。
somehost 162.242.195.82
otherhost 50.31.209.229"
Compose file: network_mode
network_mode: “host”
Find a quick reference for Docker Compose version 3, including Docker Engine compatibility, memory limitations, and more.
Composeによる各コンテナをホスト側のネットワークと隔離するため、ネットワークモードをブリッジモードにしますが、この条件でWebRTC関連のコンテナなどで出入り口となるポートを多く割り当てた場合、メモリーオーバフローが発生します。以下のガイドラインでも提示されていますが、広範なポートレンジが必要となるケースでは、ネットワークモードをホスト(ホストPCのローカルIP)とします。ホストモードにした場合、ポートオプションは全て無効になります。
<備考>Kurento, FreeSwitch各コンテナによるポート割当てメモリーオーバフロー発生対策
docker-composeの各サービス(Dockerコンテナ)のアップデート
docker images
コマンドによりサービスイメージの作成日時 CREATED や TAG を確認、以下のどちらかの手順でイメージをアップデートします。
(1) tagの変更によりアップデート
または、
(2) 同じtagでも更新されている最新版に置換えます。
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
instrumentisto/coturn latest 170432ce18ed 7 days ago 18.8MB
jitsi/jvb stable-4857 3a8230193b79 6 months ago 279MB
jitsi/jicofo stable-4857 25d2695a841c 6 months ago 292MB
jitsi/prosody stable-4857 392f733226f0 6 months ago 105MB
jitsi/web stable-4857 1fad75476320 6 months ago 483MB
(1) tagの変更によりアップデートする場合
docker-compose ファイルの各サービスのtag 、ビルドリンク先のdockerfile のtag を置換えます。
docker-compose down
コマンドにより稼働中のサービスコンテナを停止・削除します。
$ docker-compose down
以下ビルドオプション(--build
:リンク先dockerfile がある場合)を追加して各サービスコンテナを起動することで、新規イメージのダウンロードと、そのイメージによるコンテナが起動します。
$ docker-compose up -d --build
docker imeges
コマンドでtag を確認し、使用しなくなったイメージは削除して下さい。
(2) 同じtagでも更新されている最新版に置換える場合
docker-compose down
コマンドにより稼働中のサービスコンテナを停止・削除します。
$ docker-compose down
docker pull
コマンドにより新規イメージをダウンロードしてアップデートします。
$ docker pull image/name:tag
各サービスコンテナを起動します。新規イメージにより各サービスコンテナが稼働します。
$ docker-compose up -d
旧イメージのtag には <none>
が付与されるので、イメージIDを確認して以下コマンドで削除して下さい。
$ docker rmi imege-ID
docker-composeファイル内の任意のサービスのみをビルドする場合
$ docker-compose build <service_name>
docker compose pullコマンドによるイメージアップデート
$ docker compose down
$ docker compose pull
$ docker compose up -d
$ docker image prune -f
docker-composeファイルに - ${DOCKER_PATH}:/usr/bin/docker:ro
を追加して起動
$ DOCKER_PATH=$(which docker) docker-compose up -d
Dockerfile for systemd base image
systemd ベースのイメージから、systemctl によるアプリ起動を有効にすることで、dockerfileによるマルチサービスの起動が出来るようになります。
CentOS DockerHub
https://hub.docker.com/_/centos
FROM centos:7
ENV container docker
RUN (cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ $i == \
systemd-tmpfiles-setup.service ] || rm -f $i; done); \
rm -f /lib/systemd/system/multi-user.target.wants/*;\
rm -f /etc/systemd/system/*.wants/*;\
rm -f /lib/systemd/system/local-fs.target.wants/*; \
rm -f /lib/systemd/system/sockets.target.wants/*udev*; \
rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \
rm -f /lib/systemd/system/basic.target.wants/*;\
rm -f /lib/systemd/system/anaconda.target.wants/*;
VOLUME [ "/sys/fs/cgroup" ]
CMD ["/usr/sbin/init"]
This Dockerfile deletes a number of unit files which might cause issues. From here, you are ready to build your base image.
$ docker build --rm -t local/c7-systemd .
Example systemd enabled app container
In order to use the systemd enabled base container created above, you will need to create your Dockerfile
similar to the one below.
FROM local/c7-systemd
RUN yum -y install httpd; yum clean all; systemctl enable httpd.service
EXPOSE 80
CMD ["/usr/sbin/init"]
Build this image:
$ docker build --rm -t local/c7-systemd-httpd .
Running a systemd enabled app container
In order to run a container with systemd, you will need to mount the cgroups volumes from the host. Below is an example command that will run the systemd enabled httpd container created earlier.
$ docker run -ti -v /sys/fs/cgroup:/sys/fs/cgroup:ro -p 80:80 local/c7-systemd-httpd
This container is running with systemd in a limited context, with the cgroups filesystem mounted. There have been reports that if you’re using an Ubuntu host, you will need to add -v /tmp/$(mktemp -d):/run
in addition to the cgroups mount.
Allow FUSE functionality by default
opened 09:01AM - 29 May 18 UTC
* [ ] This is a bug report
* [x] This is a feature request
* [x] I searched ex… isting issues before opening this one
### Expected behavior
Mounting FUSE filesystems should work out-of-the box, because it is safe. It fits within the idea of a containerized app.
### Actual behavior
An attempt to mount a FUSE filesystem fails with:
`fuse: device not found, try 'modprobe fuse' first`
or
`fuse: failed to exec fusermount: No such file or directory`
The only way to fix it is to run the container with **additional permissions**:
`--cap-add SYS_ADMIN --device /dev/fuse`
This makes it very difficult to run FUSE inside Docker because it is often all but impossible to run with additional flags in a managed environment.
### Steps to reproduce the behavior
```
git clone https://github.com/rustyx/fuse-hello.git
docker build fuse-hello -t hello
docker run -it hello
docker run -it --device /dev/fuse hello
docker run -it --cap-add SYS_ADMIN --device /dev/fuse hello
```
**Output of `docker version`:**
```
Client:
Version: 18.01.0-ce
API version: 1.35
Go version: go1.9.2
Git commit: 03596f51b1
Built: Thu Jan 11 22:29:41 2018
OS/Arch: windows/amd64
Experimental: false
Orchestrator: swarm
Server:
Engine:
Version: 18.05.0-ce
API version: 1.37 (minimum version 1.12)
Go version: go1.10.1
Git commit: f150324
Built: Wed May 9 22:20:42 2018
OS/Arch: linux/amd64
Experimental: false
```
コンテナへのFUSEファイルシステムのマウントオプション
--cap-add SYS_ADMIN --device /dev/fuse
--cap-add SYS_ADMIN
は省略可?(未確認)
moby:master
← t0rr3sp3dr0:feat/mount-fuse
opened 04:35AM - 14 Jan 21 UTC
<!--
Please make sure you've read and understood our contributing guidelines;
… https://github.com/moby/moby/blob/master/CONTRIBUTING.md
** Make sure all your commits include a signature generated with `git commit -s` **
For additional information on our contributing process, read our contributing
guide https://docs.docker.com/opensource/code/
If this is a bug fix, make sure your description includes "fixes #xxxx", or
"closes #xxxx"
Please provide the following information:
-->
Fixes docker/for-linux#321
**- What I did**
Kernel 4.18 enabled safe unprivileged FUSE mounts within a user namespace, thus no SYS_ADMIN capability should be required to mount FUSE filesystems inside a container on newer kernels. But the default profiles for AppArmor and SecComp block some syscalls that are necessary for this to work, so I changed the default profiles for AppArmor and SecComp to allow unprivileged FUSE mounts.
**- How I did it**
On AppArmor, I allowed mount operations with fstype `fuse` and `fuse.*` and removed the deny rule for `mount`.
On SecComp, it is not possible to check the fstype for the mount calls and I had to whitelist all calls. Additionally, I allowed umount calls (these were already allowed by the AppArmor profile) and unshare calls (that should be already allowed as the documentation says that `unshare --user` doesn't require CAP_SYS_ADMIN: https://docs.docker.com/engine/security/seccomp/#significant-syscalls-blocked-by-the-default-profile).
**- How to verify it**
Run `apparmor.InstallDefault("mount-fuse")` with this patch applied to load the `mount-fuse` profile into AppArmor.
https://github.com/moby/moby/blob/41e5d459f1725546b58579fea585afb83ca389bc/profiles/apparmor/apparmor.go#L70
Copy the contents of the SecComp profile to a file called `mount-fuse.json`.
https://github.com/moby/moby/blob/41e5d459f1725546b58579fea585afb83ca389bc/profiles/seccomp/default.json#L1
Start a new container by executing the following line:
```bash
docker run --rm --device /dev/fuse --security-opt apparmor=mount-fuse --security-opt seccomp=mount-fuse.json -it ubuntu
```
Inside the container, install `sshfs`.
```bash
apt-get update
apt-get install -y sshfs
```
Unshare the user and mount namespaces. (I'm not sure yet why this is necessary)
```bash
# before the patch this would fail with "unshare: unshare failed: Operation not permitted"
unshare -mr --propagation unchanged
```
Inside the new namespaces, try mounting a filesystem with `sshfs`.
```bash
# before the patch this would fail with "fuse: mount failed: Permission denied"
# now it fails with "read: Connection reset by peer", but if you point to a real SSH server it works
sshfs user@localhost:/ /mnt
```
**- Description for the changelog**
<!--
Write a short (one line) summary that describes the changes in this
pull request for inclusion in the changelog:
-->
Change default AppArmor and SecComp profiles to allow unprivileged FUSE mounts.
**- A picture of a cute animal (not mandatory but encouraged)**
![](https://user-images.githubusercontent.com/7753096/104544936-c8e2d200-5607-11eb-80c3-c512c146943c.jpg)
マルチステージビルドによるイメージファイル容量削減
Dockerfile によりビルドしたアプリを、そのままコンテナとして使用する場合、作成されるイメージ容量はビルドツールによって肥大化します。
このビルド・インストールされたアプリを、マルチステージにより、そのまま別のイメージへ引継ぐことでビルドツールによるイメージ容量肥大化を回避します。
EX)
golang イメージによりビルドされたアプリを、アプリに必要なユーティリティと共にalpine イメージへ引継ぎます。
FROM golang:1.7.3 AS builder
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html
COPY app.go .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/github.com/alexellis/href-counter/app .
CMD ["./app"]
Dockerコンテナ内からホストマシンのGPIO制御
https://stackoverflow.com/questions/30059784/docker-access-to-raspberry-pi-gpio-pins
上記に加え、例えばGPIO を制御する場合、
$ docker run --cap-add SYS_RAWIO -d <container_name>
Dockerコンテナ内でのバッシュプロンプトのカスタマイズ
https://wiki.archlinux.org/title/Bash/Prompt_customization
ベースOSがUbuntu の場合、コンテナ内でのバッシュプロンプト表示は
user@container_ID:Current_Directory # command
となりますが、このバッシュプロンプト表示をカスタマイズする場合は Dockerfile
で以下のように指定します。
テキストカラーとDockerIDの指定
ENV PS1='\[\e[34m\]\u@bc-dev-centos7>\[\e[0m\] '
\e : an ASCII escape character (033)
34m : text color —> Blue
0m : text no color
https://www.cyberciti.biz/tips/howto-linux-unix-bash-shell-setup-prompt.html
ビルド中に停止したDockerイメージの中身確認
イメージビルドが失敗した場合コンテナが途中で停止します。停止時点でのDockerfileで指定した失敗したタスクを確認する際に便利なティップスです。
docker
停止コンテナの確認
$ docker ps -a
コンテナIDからイメージの作成
$ docker commit $CONTAINER_ID user/test_image
イメージからコンテナ起動しシェル起動
$ docker run -ti user/test_image bash
コンテナ内のシェルでインストールしたパッケージファイル等を確認して下さい。
tk-fuse
2021 年 10 月 18 日午前 11:30
38
How to run a cron job inside a docker container
Dockerコンテナ内でクローンジョブ実行
linux, docker, cron
Here is how I run one of my cron containers.
Dockerfile:
FROM alpine:3.3
ADD crontab.txt /crontab.txt
ADD script.sh /script.sh
COPY entry.sh /entry.sh
RUN chmod 755 /script.sh /entry.sh
RUN /usr/bin/crontab /crontab.txt
CMD ["/entry.sh"]
crontab.txt
*/30 * * * * /script.sh >> /var/log/script.log
entry.sh
フォアグラウンド、ログレベルオプション指定
#!/bin/sh
# start cron
/usr/sbin/crond -f -l 8
script.sh
#!/bin/sh
# code goes here.
echo "This is a script, run by cron!"
Build like so
docker build -t mycron .
Run like so
docker run -d mycron
バックアップ:外部ボリューム、イメージ
外部ボリュームのバックアップとリストア
既存のDockerボリューム: f9e_pma
を新たなホストに移行する際のバックアップとリストア手順
Backup
1. $ docker run -v f9e_pma:/f9e_pma --name dbstore ubuntu /bin/bash
2. $ docker run --rm --volumes-from dbstore -v $(pwd)/docker_volume_backup:/backup ubuntu tar cvf /backup/backup.tar /f9e_pma
3. $ docker rm dbstore
外部ボリューム f9e_pma
を取り込んだDockerコンテナ dbstore
を起動
コンテナ dbstore
のボリュームをマウントした新たなコンテナ内で、取り込んだディレクトリ f9e_pma
の圧縮ファイルを作成。圧縮ファイルはホストマシンの指定ディレクトリ docker_volume_backup
に保存される。
コンテナ dbstore
の削除
Restore
$ docker volume create f9e_pma
$ docker run -v f9e_pma:/f9e_pma --name dbstore2 ubuntu /bin/bash
$ docker run --rm --volumes-from dbstore2 -v $(pwd)/docker_volume_backup:/backup ubuntu bash -c "cd /f9e_pma && tar xvf /backup/backup.tar --strip 1"
$ docker rm dbstore2
Dockerイメージの保存と読み込み
イメージの作成と再読込については下記参照(本記事内)
docker save / docker load
イメージのバックアップ、他ホストへの移行(docker load)
$ docker save -o <path for generated tar file> <image name>
$ docker load -i <path to image tar file>
Dockerイメージを確認しタグ付きでtarファイルで出力 …
Docker-Composeコマンドによるイメージのアップデート
注)前回のビルドキャッシュを削除すること。
$ docker builder prune --all
docker, docker-compose
$ docker-compose pull
$ docker-compose up --force-recreate --build -d
$ docker image prune -f
Docke-Composeファイルで指定したイメージ(サービス)を個々にアップデートする場合
docker-compose.yml
services:
.....
.....
mariadb:
container_name: mariadb
image: mariadb:latest
.....
.....
イメージを docker pull
コマンドで更新後、 docker-compose
ファイルが格納されているディレクトリで docker compose up -d
を実行し、コンテナを再構築・起動します。
この場合、事前に docker compose down
コマンドでコンテナの停止・削除をする必要はありません。
$ docker pull mariadb:latest
$ cd docker_compose_project_directory
$ docker compose up -d
Docker-Composeファイル内でbuildオプションにより、独自の dockerfile
を指定している場合
docker-compose.yml
services:
.....
.....
nginx:
container_name: nginx
build:
context: ./docker_files
dockerfile: nginx-alpine
.....
.....
dockerfile
内で指定したイメージを docker pull
コマンドによりアップデートし、 docker-compose
ファイルが格納されているディレクトリで docker compose build service_name
を実行し、イメージを再構築します。
$ docker pull nginx:alpine
$ docker compose build nginx
イメージを再構築後 docker compose up -d
を実行し、コンテナを再構築・起動します。
この場合、事前に docker compose down
コマンドでコンテナの停止・削除をする必要はありません。
$ docker compose up -d
Docker-Composeファイル環境変数フォーマット
.env
ファイルで docker-compose.yml
内の変数を定義できますが、その書式は以下の通りです。
Both $VARIABLE
and ${VARIABLE}
syntax are supported. Additionally when using the 2.1 file format , it is possible to provide inline default values using typical shell syntax:
${VARIABLE:-default}
evaluates to default
if VARIABLE
is unset or empty in the environment.
${VARIABLE-default}
evaluates to default
only if VARIABLE
is unset in the environment.
Similarly, the following syntax allows you to specify mandatory variables:
${VARIABLE:?err}
exits with an error message containing err
if VARIABLE
is unset or empty in the environment.
${VARIABLE?err}
exits with an error message containing err
if VARIABLE
is unset in the environment.
deploy
Find a quick reference for Docker Compose version 3, including Docker Engine compatibility, memory limitations, and more.
Added in version 3 file format.
Specify configuration related to the deployment and running of services. This only takes effect when deploying to a swarm with docker stack deploy , and is ignored by docker-compose up
and docker-compose run
.
version: "3.9"
services:
redis:
image: redis:alpine
deploy:
replicas: 6
placement:
max_replicas_per_node: 1
update_config:
parallelism: 2
delay: 10s
restart_policy:
condition: on-failure
deploy
は docker-compose up -d
コマンドでは無効 となります。
opened 03:29PM - 27 Feb 19 UTC
closed 05:09PM - 16 Oct 20 UTC
stale
docker-compose version 1.22.0, build f46880fe
Docker Engine 18.09.2
docker-… compose.yml
```version: '3.4'
services:
hello:
image: nginx
deploy:
replicas: 2
update_config:
parallelism: 1
delay: 1s
restart_policy:
condition: on-failure
```
WARNING: Some services (hello) use the 'deploy' key, which will be ignored. Compose does not support 'deploy' configuration - use `docker stack deploy` to deploy to a swarm.
deploy not work
docker buildx ビルドの拡張機能
Working with Docker Buildx
https://docs.docker.com/build/buildx/
Reference
クロスプラットフォームでビルド
$ docker buildx build --push --platform linux/arm64/v8,linux/amd64 --tag xxx/nginx-proxy:1.21-alpine