2014年11月20日 星期四

[Linux] Docker 使用筆記 - 透過 Supervisor 開機執行多項服務(SSH, Apache Web Server, MySQL) @ Ubuntu 14.04

前陣子把玩 Docker 時,粗略知道運作是著重落在一隻 process 上,在 Dockerfile 中雖然可以執行多個 CMD,但擺上多隻會共同運行指令仍是無效的。解法的原理就是執行一隻程式,由那支程式管理其他程式。在 Docker 官方文件上就是使用 Supervisor 啦:Using Supervisor with Docker

Dockefile:

FROM ubuntu:14.04
RUN apt-get update
RUN sudo -E "DEBIAN_FRONTEND=noninteractive" apt-get install -y telnet curl mysql-server-5.6 apache2 php5 php5-mysql openssh-server supervisor
RUN mkdir -p /var/lock/apache2 /var/run/apache2 /var/run/mysqld /var/run/sshd /var/log/supervisor

COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf

RUN mkdir -p /root/.ssh/ && chmod 700 /root/.ssh/
COPY id_rsa.pub /root/.ssh/authorized_keys
RUN chmod 600 /root/.ssh/authorized_keys

EXPOSE 22 80 3306
CMD ["/usr/bin/supervisord"]


supervisord.conf:

[supervisord]
nodaemon=true

[program:sshd]
command=/usr/sbin/sshd -D

[program:apache2]
command=/bin/bash -c "source /etc/apache2/envvars && exec /usr/sbin/apache2 -DFOREGROUND"

[program:mysql]
command=/usr/bin/pidproxy /var/run/mysqld/mysqld.pid /usr/sbin/mysqld
autorestart=true


id_rsa / id_rsa.pub:

$ ssh-keygen -t rsa -f id_rsa -P''

上述檔案都在同一層目錄中,分別有 Dockefile, supervisord.conf, id_rsa 和 id_rsa.pub ,共四個檔案。

接著建立 Image:

$ cd /path/dir
$ sudo docker build -t dev .


運行,將本機端的 10022, 10080, 13306 分別對應到 Docker Container 的 22, 80, 3306:

$ sudo docker run -t -p 10022:22 -p 10080:80 -p 13306:3306 dev
/usr/lib/python2.7/dist-packages/supervisor/options.py:295: UserWarning: Supervisord is running as root and it is searching for its configuration file in default locations (including its current working directory); you probably want to specify a "-c" argument specifying an absolute path to a configuration file for improved security.
  'Supervisord is running as root and it is searching '
CRIT Supervisor running as root (no user in config file)
WARN Included extra file "/etc/supervisor/conf.d/supervisord.conf" during parsing
INFO RPC interface 'supervisor' initialized
CRIT Server 'unix_http_server' running without any HTTP authentication checking
INFO supervisord started with pid 1
INFO spawned: 'sshd' with pid 9
INFO spawned: 'mysql' with pid 10
INFO spawned: 'apache2' with pid 11
INFO success: sshd entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)
INFO success: mysql entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)
INFO success: apache2 entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)
...


也可以按 ctrl+c 離開,但 VM 還會繼續跑

遠端登入:

$ ssh -i /path/dir/id_rsa root@localhost:10022

若有需求想要 console 端登入:

$ sudo docker ps -a
$ sudo docker inspect --format '{{.State.Pid}}' CONTAINER_ID
$ sudo nsenter --target PID_NUMBER --mount --uts --ipc --net --pid


收工!

沒有留言:

張貼留言