15
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Fabricを使用してDockerイメージを生成する

Posted at

概要

Fabricを使用して、Dockerイメージを作成してみます。FabricはSSH経由での操作しか行えないため、Dockerに対して、SSH経由で操作を行う必要があります。

まず、下記の処理を行う関数dockerを定義します。

  • SSH可能なDockerイメージを生成し、sshdをDockerコンテナ内で起動可能にする。
  • Fabricで、タスク開始前に実行する関数(docker)を定義し、sshdをDockerコンテナで実行する。
  • 終了前にDockerコンテナへの変更をcommitする。
import atexit
import time
from fabric.api import *
from fabric.contrib.console import confirm


@task
def docker():
    env.hosts = ['127.0.0.1:2222']
    env.user = 'root'
    env.password = 'PASSWORD'

    import docker
    cl = docker.Client()
    container = cl.create_container('BASE_IMAGE_NAME',
                                    command='/usr/sbin/sshd -D',
                                    ports=[22])

    cl.start(container, port_bindings={22:2222})
    time.sleep(3)

    @atexit.register
    def commit():
        cl.stop(container)
        if confirm('Commit container changes?', default=True):
            cl.commit(container['Id'], repository='IMAGE_NAME', tag='TAG')

下記をfabfile.pyに記述することで、

$ fab docker TASK_NAME

のように実行することが可能になります。

また、上記のcommit関数内でdocker pushなどを自動化して実行すると、タスクの実行からDocker Indexのアップロードまでを全て自動化することができます。

なお、実行には、docker-pyが必要です。

15
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?