Hello docker 〜その2
単独でdockerを動かせたので、今回はデータベース(postgres)を作成。
これはdockerのサイトにそのまんまあるので、それを参考に作成。
Dockerizing PostgreSQL
準備
docker-myPostgresディレクトリを作成し、
schema.sql,masterdata.sql,data.sqlを置く。
docker-myApplication
├─schema.sql
├─masterdata.sql
└─data.sql
Dockerfileの作成
FROM ubuntu # PostgreSQLのインストール RUN apt-key adv --keyserver keyserver.ubuntu.com --recv-keys B97B0AFCAA1A47F044F244A07FCC7D46ACCC4CF8 RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ precise-pgdg main" > /etc/apt/sources.list.d/pgdg.list RUN apt-get update && \ apt-get install -y \ python-software-properties \ software-properties-common \ postgresql-9.4 \ postgresql-client-9.4 \ postgresql-contrib-9.4 # 実行ユーザーの宣言 USER postgres # ユーザとデータベースの作成 RUN /etc/init.d/postgresql start &&\ psql --command "CREATE USER scott WITH SUPERUSER PASSWORD 'tiger';" &&\ createdb -O scott mydatabase --encoding=UTF8 --template=template0 # ネットワーク系の設定 RUN echo "host all all 0.0.0.0/0 md5" >> /etc/postgresql/9.4/main/pg_hba.conf RUN echo "listen_addresses='*'" >> /etc/postgresql/9.4/main/postgresql.conf # ポートをコンテナ間ネットワークに公開 EXPOSE 5432 RUN ls # DDLの追加と実行 ADD schema.sql ./schema.sql ADD masterdata.sql ./masterdata.sql ADD data.sql ./data.sql RUN /etc/init.d/postgresql start &&\ psql fa < ./schema.sql &&\ psql fa < ./masterdata.sql &&\ psql fa < ./data.sql # コンテナイメージが起動した時のコマンド CMD ["/usr/lib/postgresql/9.4/bin/postgres", \ "-D", "/var/lib/postgresql/9.4/main", \ "-c", "config_file=/etc/postgresql/9.4/main/postgresql.conf"]
docker imageの作成
$ docker build -t myPostgres ./
docker container 起動
$ docker run --name mydb myPostgres
Container linking で接続確認
$ docker run --rm -t -i --link mydb:pg myPostgres bash postgres@0b197bc3ddf9:/$ postgres@0b197bc3ddf9:/$ postgres@0b197bc3ddf9:/$ psql -h $PG_PORT_5432_TCP_ADDR -p $PG_PORT_5432_TCP_PORT -d mydatabase -U scott Password for user scott: psql (9.4.4) SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off) Type "help" for help.
ホストOSから 接続確認
-P をつけて、containerを起動する。
$ docker run -P --name mydb myPostgres
ホストOSのipアドレスを調べる
$ boot2docker ip 192.168.59.103
ポートを調べる。
$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 3dc0112e6390 myPostgres "/usr/lib/postgresql 13 hours ago Up 57 seconds 0.0.0.0:32771->5432/tcp mydb
psqlで接続
$ psql -h 192.168.59.103 -p 32771 -d mydatabase -U scott Password for user scott: psql (9.4.0, server 9.4.4) SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off) Type "help" for help. mydatabase=#
dockerのサイトと違うところ
データベースでは日本語を使いたため、データベース作成時のコマンドに
--encoding=UTF8 --template=template0
を追加