[GCP] Google cloud Docker-compose wordpress 구성

 

도메인만 있으면 1년간 무료로 쓸수 있는 Google cloud 를 이용하여 WordPress 를 구성하여 사용하는것도 좋을거 같습니다. 🙂

기존 생성했던 VM 을 사용 하기 때문에 최초로 만든 vm 이미지에서 수정을 합니다.

Compute Engine -> VM 인스턴스 -> 인스턴스 이름 클릭 후 수정을 클릭합니다.

 

초소형(공유vCPU 1개) -> 소형 (공유 vCPU 1개) 로 변경후 저장을 클릭합니다.

 

VM 인스턴스를 시행후 SSH로 접속을 합니다.

 

docker 설치

test@ubuntu-trusty-1:~$ curl -s https://get.docker.com/ | sudo sh
test@ubuntu-trusty-1:~$ sudo usermod -aG docker test

터미널을 재접속 합니다.

 

docker 설치 확인

test@ubuntu-trusty-1:~$ docker --version
Docker version 18.02.0-ce, build fc4de44
test@ubuntu-trusty-1:~$

 

docker-compose 설치

test@ubuntu-trusty-1:~$ sudo curl -L https://github.com/docker/compose/releases/download/1.19.0/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   617    0   617    0     0   2762      0 --:--:-- --:--:-- --:--:--  2766
100 8288k  100 8288k    0     0  7366k      0  0:00:01  0:00:01 --:--:-- 17.6M
test@ubuntu-trusty-1:~$ sudo chmod +x /usr/local/bin/docker-compose
test@ubuntu-trusty-1:~$ docker-compose --version
docker-compose version 1.19.0, build 9e633ef
test@ubuntu-trusty-1:~$

 

Nginx-proxy container

test@ubuntu-trusty-1:~$ mkdir -p web-service/nginx-proxy
test@ubuntu-trusty-1:~$ cd web-service/nginx-proxy/
test@ubuntu-trusty-1:~/web-service/nginx-proxy$ vi docker-compose.yml
version: "3"

services:
  nginx-proxy:
    image: jwilder/nginx-proxy
    container_name: nginx-proxy
    ports:
      - "80:80"
    volumes:
      - /var/run/docker.sock:/tmp/docker.sock:ro
    restart: always

networks:
  default:
    external:
      name: nginx-proxy

 

Nginx-proxy container 실행

test@ubuntu-trusty-1:~/web-service/nginx-proxy$ docker network create nginx-proxy
6e66bd966be8c43541585319e0516c3350d5b1d852789ca4efd93ee9ef446589
test@ubuntu-trusty-1:~/web-service/nginx-proxy$ docker-compose up -d --build
test@ubuntu-trusty-1:~/web-service/nginx-proxy$ docker ps
CONTAINER ID        IMAGE                 COMMAND                  CREATED             STATUS              PORTS                NAMES
b4bbe5ac5015        jwilder/nginx-proxy   "/app/docker-entrypo…"   4 seconds ago       Up 3 seconds        0.0.0.0:80->80/tcp   nginx-proxy
test@ubuntu-trusty-1:~/web-service/nginx-proxy$

 

 

WordPress container

blog docker-compose.yml 파일 생성

test@ubuntu-trusty-1:~$ mkdir -p web-service/blog
test@ubuntu-trusty-1:~$ cd web-service/blog/
test@ubuntu-trusty-1:~/web-service/blog$ mkdir web-data
test@ubuntu-trusty-1:~/web-service/blog$ mkdir db-data
test@ubuntu-trusty-1:~/web-service/blog$ vi docker-compose.yml
 version: "3"

services:
  db:
     image: mariadb
     volumes:
       - ./db-data:/var/lib/mysql
     restart: always
     environment:
       MYSQL_ROOT_PASSWORD: test1234
       MYSQL_DATABASE: wordpress
       MYSQL_USER: wordpress
       MYSQL_PASSWORD: test1234
     container_name: wp_blog_db

  wordpress:
     image: wordpress:latest
     expose:
       - 80
     restart: always
     volumes:
       - ./web-data:/var/www/html
     environment:
       VIRTUAL_HOST: blog.crois.net
       WORDPRESS_DB_HOST: db:3306
       WORDPRESS_DB_USER: wordpress
       WORDPRESS_DB_PASSWORD: test1234
     container_name: wp_blog

networks:
  default:
    external:
      name: nginx-proxy

 

WordPress container 실행

test@ubuntu-trusty-1:~$ cd web-service/blog/
test@ubuntu-trusty-1:~/web-service/blog$ docker-compose up -d --build
~중략
실행확인
test@ubuntu-trusty-1:~/web-service/blog$ docker ps
CONTAINER ID        IMAGE                 COMMAND                  CREATED              STATUS              PORTS                NAMES
7d728447bde6        mariadb               "docker-entrypoint.s…"   8 seconds ago        Up 7 seconds        3306/tcp             wp_blog_db
9415c6dd76e1        wordpress:latest      "docker-entrypoint.s…"   8 seconds ago        Up 7 seconds        80/tcp               wp_blog
b4bbe5ac5015        jwilder/nginx-proxy   "/app/docker-entrypo…"   About a minute ago   Up About a minute   0.0.0.0:80->80/tcp   nginx-proxy
test@ubuntu-trusty-1:~/web-service/blog$

 

web browser 에서 http://blog.crois.net 을 연결 합니다.

수고 하셨습니다. 🙂

 

 

 

 

[GCP] Google cloud 외부 IP 주소 연결 (고정IP 설정)

 

VPC 네트워크 -> 외부 IP 주소 를 클릭합니다.

고정 주소 예약을 클릭합니다.

 

이름을 지정합니다. 지역에서 Zone 을 설정 할수 있습니다.

 

예약 버튼을 클릭합니다.

 

외부 IP 주소 연결이 생성 되었습니다.

 

Compute Engine -> VM 인스턴스 항목으로 이동 합니다.

vm 이름을 클릭 합니다. (ubuntu-trusty-1)

 

 

 

VM 인스턴스 세부정부 에서 네트워크 인터페이스 항목 nic0: default default 를 클릭합니다.

 

외부 IP 항목 에서 임시를 클릭한후 IP 주소만들기를 선택합니다.

 

새 고정 IP 주소 예약 에서 test01 을 입력합니다.

 

예약을 클릭합니다.

 

최하단으로 이동하여 저장을 클릭합니다.

 

ssh 연결 테스트를 진행 합니다.

[GCP] Google Cloud ssh-key 이용하여 접속

Linux 의 경우 ssh-keygen 명령어를 통하여 아래와 같이 RSA 키페어를 생성 하고,

Windows는 puttygen 을 이용하여 RSA 키페어를 생성 합니다.

Global 모든 Cloud 인스턴스에 접속시 메타데이터 ssh 키 부분에 설정 하시면 되며 단인 Cloud 인스턴스만 접속하기 위해선 Compute Engine -> VM 인스턴스 세부정보 부분의

SSH 키 부분에 등록 하시면 됩니다.

 

Linux 나 MacOS 이용시

RSA 키페어 생성

주의: 키페어 생성시 반드시 Password 를 입력해야 합니다.

엔터를 눌러 스킵시 정상적으로 접속할수 없습니다.

test@docker-test:~$ ssh-keygen -t rsa -C "test@google.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/test/.ssh/id_rsa):
Created directory '/home/test/.ssh'.
Enter passphrase (empty for no passphrase):       // Password 입력
Enter same passphrase again:                      // Password 입력
Your identification has been saved in /home/test/.ssh/id_rsa.
Your public key has been saved in /home/test/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:cJ23OKMOchEWj3oIpyMBKPvdDXlYoeChKovlBuIj1ok test@google.com
The key's randomart image is:
+---[RSA 2048]----+
|o   o . ..       |
|+  o o =.. .     |
|o.o o *+o o .    |
|.o + +++.  o .   |
|*.+.o.o+S + .    |
|=*+.o..... o     |
|+Eoo. o .        |
|o..  o o         |
|        .        |
+----[SHA256]-----+
test@docker-test:~$

키생성시 사용하는 암호를 통하여 ssh 로 접속을 하게 됩니다.

 

id_rsa.pub 퍼블릭키 위치

test@docker-test:~/.ssh$ pwd
/home/test/.ssh
test@docker-test:~/.ssh$ ls
id_rsa  id_rsa.pub
test@docker-test:~/.ssh$

해당 파일(id_rsa.pub) 을 scp 로 Copy 후 Google 클라우드에 등록 합니다.

 

퍼블릭 키 등록

compute engine -> 메타데이터 -> SSH키로 이동 합니다.

+항목추가를 클릭하여 ~/.ssh/id_rsa.pub 내용을 붙여 넣기 합니다.

메타데이터에 key를 추가 하게 되면 해당 키를 통하여 모든 인스턴스에 접속 가능합니다.

저장을 클릭합니다.

 

 ssh 접속

사용하고 있는 Linux 머신에서 접속시 아래와 같은 방법으로 접속하실수 있습니다.

test@docker-test:~/.ssh$ ssh -i id_test google_user@35.xx.xx.200
Warning: Identity file id_test.pub not accessible: No such file or directory.
The authenticity of host '35.xx.xx.200 (35.xx.xx.200)' can't be established.
ECDSA key fingerprint is SHA256:IEUCgjm+1KuzORwPmQH/Vo6SnCztScOWBehFCoSOveo.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '35.xx.xx.200' (ECDSA) to the list of known hosts.
Enter passphrase for key '/home/test/.ssh/id_rsa':
Welcome to Ubuntu 14.04.5 LTS (GNU/Linux 4.4.0-112-generic x86_64)

 * Documentation:  https://help.ubuntu.com/

  System information as of Tue Feb 27 08:14:28 UTC 2018

  System load:  0.0               Processes:           80
  Usage of /:   12.3% of 9.81GB   Users logged in:     0
  Memory usage: 14%               IP address for eth0: xx.xx.0.2
  Swap usage:   0%

  Graph this data and manage this system at:
    https://landscape.canonical.com/

  Get cloud support with Ubuntu Advantage Cloud Guest:
    http://www.ubuntu.com/business/services/cloud

0 packages can be updated.
0 updates are security updates.

New release '16.04.3 LTS' available.
Run 'do-release-upgrade' to upgrade to it.

Your Hardware Enablement Stack (HWE) is supported until April 2019.

Last login: Tue Feb 27 08:14:28 2018 from xx.xxx.xx.164
test@ubuntu-trusty-1:~$

 

 

 

Windows 이용시

puttygen 을 이용하여 RSA 키페어를 생성 합니다.

링크에서 iPutty  를 다운 받을수 있습니다.
https://github.com/iPuTTY/iPuTTY/releases

생성버튼 클릭

개인키 저장 버튼을 클릭 합니다.

 

개인키 instance_name.ppk 으로 저장합니다.

아래 부분을 복사 하여 퍼블릭키를 등록 합니다.

 

Google Cloud 에서 Compute Engine -> 메타데이타 -> SSH 키로 이동합니다.

저장을 클릭합니다.

 

ssh-client 를 실행합니다. (putty 이용)

 

Connection -> SSH -> Auth 로 이동후 Browse… 에서 저장한 키파일을 불러 옵니다.

Open 을 클릭 합니다. 

 

접속후 화면

 

단일 인스턴스 접속시 설정 방법

별도의 인스턴스 재시작이 필요하지 않으며 아래와 같은 방법으로 등록만 해주시면 됩니다.

Compute Engine -> VM 인스턴스

ssh key 를 추가할 인스턴스를 클릭합니다.

 

수정을 클릭합니다.

 

페이지 하단에 SSH 키 부분에 추가 하시면 됩니다.

 

페이지 하단의 저장을 클릭합니다.

 

접속시 위와 동일한 방법으로 접속 하시면 됩니다.

 

[GCP] Google Cloud 생성

https://console.cloud.google.com/?hl=ko

최초 사용시 12개월간 사용할수 있는 크레딧 $300 달러를 줍니다.

준비물 : Google 계정 , 신용카드

무료사용이 끝난후 사용료가 부과되지 않습니다 🙂

무료평가판 신청을 클릭 합니다.

사용자 등록정보 입력후 아래와 같은 화면을 볼수 있습니다.

My First Project 를 클릭합니다.

 

+버튼을 클릭하여 프로젝트를 생성합니다.

 

프로젝트 이름을 기입 합니다.

ex) docker-test

 

중간메뉴에 Cloud Launcher 를 클릭합니다.

 

Cloud Launcher 를 클릭하면 아래와 같은 화면을 볼수 있습니다.

운영체체 부분에 Ubuntu Trusty 를 클릭합니다.

 

 

 

COMPUTE ENGINE에서 실행을 클릭하여 VM 인스턴스를 생성합니다.

약 3~5분후 아래와 같은 화면을 볼수 있습니다.

vCPU 의 경우 사용량에 따라 선택 하시면 됩니다.

테스트로 만들기 위하여 초소형(공유 vCPU 1개) 0.6GB , f1-micro 를 선택 합니다.

영역에서 리전을 선택 할수 있습니다. asia-northeast1 도쿄 리전을 선택 합니다.

리전확인 참고: https://cloud.google.com/about/locations/?hl=ko

체크항목

모든 Cloud API에 대한 전체 액세스 허용

HTTP 트래픽 허용

HTTPS 트래픽 허용

관리, 디스크, 네트워킹, SSH 키 를 눌러 세부설정을 할수 있습니다.

만들기 버튼을 클릭합니다.

 

IP 부분의 경우 보안상 삭제 하였습니다. 

브라우저 창에서 열기를 클릭 합니다.

 

패키지 설치시 apt-get / apt 명령어를 사용하기 위하여 sudo passwrd 로 root 패스워드를 설정합니다.

test@ubuntu-trusty-1:~$ sudo passwd
Enter new UNIX password: 
Retype new UNIX password: 
passwd: password updated successfully
test@ubuntu-trusty-1:~$

 

sudo apt update 를 테스트 합니다.

 

docker swarm mode 구성

description:

To use Docker in swarm mode, install Docker. See installation instructions for all operating systems and platforms.

Current versions of Docker include swarm mode for natively managing a cluster of Docker Engines called a swarm. Use the Docker CLI to create a swarm, deploy application services to a swarm, and manage swarm behavior.

If you are using a Docker version prior to 1.12.0, you can use standalone swarm, but we recommend updating.

official page: https://docs.docker.com/engine/swarm/

 

vm 준비

docker-manager 192.168.192.10

docker-worker01 192.168.192.20

docker-worker02 192.168.192.30

3대의 vm 에는 docker가 설치 되어 있습니다.

Docker-manager
test@docker-manager:~$ docker -v
Docker version 18.02.0-ce, build fc4de44
test@docker-manager:~$

Docker-worker01
test@docker-worker01:~$ docker -v
Docker version 18.02.0-ce, build fc4de44
test@docker-worker01:~$

Docker-worker02
test@docker-worker02:~$ docker -v
Docker version 18.02.0-ce, build fc4de44
test@docker-worker02:~$

 

1. Create Docker Swarm cluster

docker-manager 에서 작업

command : docker swarm init –advertise-addr $docker-manager ip

test@docker-manager:~$ docker swarm init --advertise-addr 192.168.192.10
Swarm initialized: current node (mzsiydsvbyhafre4cppmfupvb) is now a manager.

To add a worker to this swarm, run the following command:

    docker swarm join --token SWMTKN-1-5ar8gen44ij5gi7hlkmbbhdji2e06nvod2u86e5db7zwip9707-8f5nxu48rh841xdcj0na1vp0s 192.168.192.10:2377

To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.

test@docker-manager:~$

 

docker manager node 확인

test@docker-manager:~$ docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS
mzsiydsvbyhafre4cppmfupvb *   docker-manager      Ready               Active              Leader
test@docker-manager:~$

test@docker-manager:~$ docker info
Containers: 1
~중략
Swarm: active
 NodeID: mzsiydsvbyhafre4cppmfupvb
 Is Manager: true
 ClusterID: rnqp34pegl5rj9fqd1ex30x0h
 Managers: 1
 Nodes: 1
 Orchestration:
  Task History Retention Limit: 5
 Raft:
  Snapshot Interval: 10000
  Number of Old Snapshots to Retain: 0
  Heartbeat Tick: 1
  Election Tick: 3
 Dispatcher:
  Heartbeat Period: 5 seconds
 CA Configuration:
  Expiry Duration: 3 months
  Force Rotate: 0
 Autolock Managers: false
 Root Rotation In Progress: false
 Node Address: 192.168.192.10
 Manager Addresses:
  192.168.192.10:2377
~중략

join-token 생성

docker-manager host 에서 작업

test@docker-manager:~$ docker swarm join-token worker
To add a worker to this swarm, run the following command:

    docker swarm join --token SWMTKN-1-5ar8gen44ij5gi7hlkmbbhdji2e06nvod2u86e5db7zwip9707-8f5nxu48rh841xdcj0na1vp0s 192.168.192.10:2377

test@docker-manager:~$

 

 

docker-worker swarm 등록

docker-manager에서 생성한 join-token을 이용하여 worker node 를 등록 합니다.

docker-worker01 host 에서 작업

test@docker-worker01:~$ docker swarm join  --token SWMTKN-1-5ar8gen44ij5gi7hlkmbbhdji2e06nvod2u86e5db7zwip9707-8f5nxu48rh841xdcj0na1vp0s 192.168.192.10:2377
This node joined a swarm as a worker.
test@docker-worker01:~$ docker info |grep -i swarm
WARNING: No swap limit support
Swarm: active

 

docker-worker02 host 에서 작업

test@docker-worker02:~$ docker swarm join  --token SWMTKN-1-5ar8gen44ij5gi7hlkmbbhdji2e06nvod2u86e5db7zwip9707-8f5nxu48rh841xdcj0na1vp0s 192.168.192.10:2377
This node joined a swarm as a worker.
test@docker-worker02:~$ docker info |grep -i swarm
WARNING: No swap limit support
Swarm: active
test@docker-worker02:~$

 

docker-manager node 확인

test@docker-manager:~$ docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS
mzsiydsvbyhafre4cppmfupvb *   docker-manager      Ready               Active              Leader
jvitfs6bmgr699p3nltzok0fw     docker-worker01     Ready               Active
hwkew1ktumxynqhqexjx5gn8l     docker-worker02     Ready               Active
test@docker-manager:~$

 

nginx test

docker run 의 경우 아래와 같이 사용하지만 docker swarm 의 경우 docker service create 명령어를 사용합니다.

docker run 실행시는 아래와 같이 사용 합니다. docker swarm 에서는 docker service create 명령어를 사용합니다. 🙂

test@docker-test:~$ docker run --name web-service -d -p 80:80 -p 443:443 nginx

 

docker service create 명령어

test@docker-manager:~$ docker service create --name web-service -p 80:80 -p 443:443 nginx
pgdc990uyesjmw399ayuraie9
overall progress: 1 out of 1 tasks
1/1: running   [==================================================>]
verify: Service converged
test@docker-manager:~$

 

!!! docker service create 명령어 사용시 –publish 옵션을 사용해야 합니다. 

test@docker-master:~$ docker service create --name web-service --publish 80:80 nginx
md8pzk0owb4s8ida55voqzlrb
overall progress: 1 out of 1 tasks
1/1: running   [==================================================>]
verify: Service converged
test@docker-master:~$

 

 

service 확인

test@docker-manager:~$ docker service ls
ID                  NAME                MODE                REPLICAS            IMAGE               PORTS
pgdc990uyesj        web-service         replicated          1/1                 nginx:latest        *:80->80/tcp, *:443->443/tcp
test@docker-manager:~$ docker service ps web-service
ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE            ERROR               PORTS
wd1vyqp9eg2x        web-service.1       nginx:latest        docker-manager      Running             Running 29 seconds ago
test@docker-manager:~$

 

 

docker service scale 명령어를 사용하여 service 개수를 늘려 줍니다.

service 갯수를 줄일때도 동일하게 scale을 사용 합니다.

test@docker-manager:~$ docker service scale web-service=3
web-service scaled to 3
overall progress: 3 out of 3 tasks
1/3: running   [==================================================>]
2/3: running   [==================================================>]
3/3: running   [==================================================>]
verify: Service converged
test@docker-manager:~$


test@docker-manager:~$ docker service ps web-service
ID                  NAME                IMAGE               NODE                DESIRED STATE       CURRENT STATE            ERROR               PORTS
wd1vyqp9eg2x        web-service.1       nginx:latest        docker-manager      Running             Running 20 minutes ago
bezi55mn78lf        web-service.2       nginx:latest        docker-worker01     Running             Running 42 seconds ago
vwpxbid1ez53        web-service.3       nginx:latest        docker-worker02     Running             Running 42 seconds ago
test@docker-manager:~$

 

docker service rm 

swarm 에서 사용중인 컨테이너 삭제시는 docker servier rm $service_name 으로 삭제 할수 있습니다.

test@docker-manager:~$ docker service ls
ID                  NAME                MODE                REPLICAS            IMAGE               PORTS
pgdc990uyesj        web-service         replicated          1/1                 nginx:latest        *:80->80/tcp, *:443->443/tcp
test@docker-manager:~$ docker service rm web-service
web-service
test@docker-manager:~$ docker service ls
ID                  NAME                MODE                REPLICAS            IMAGE               PORTS
test@docker-manager:~$

 

 

nginx-proxy multi-wordpress site

 

Site:https://www.draw.io

Nginx-proxy 를 이용하여 여러대의 wordpress container 사용할수 있습니다.

Nginx-proxy container 는 jwilder/nginx-proxy image 를 이용합니다.

 

Github

test@docker-test:~$ git clone https://github.com/visualwork/Docker-test.git

/Docker-test/test05 에 있습니다. 🙂

 

Nginx-proxy docker-compose.yml 파일 생성

test@docker-test:~$ mkdir -p web-service/nginx-proxy
test@docker-test:~$ cd web-service/nginx-proxy/
test@docker-test:~/web-service/nginx-proxy$ vi docker-compose.yml
## notice ##  $ docker network create nginx-proxy
version: "3"

services:
  nginx-proxy:
    image: jwilder/nginx-proxy
    container_name: nginx-proxy
    ports:
      - "80:80"
    volumes:
      - /var/run/docker.sock:/tmp/docker.sock:ro
    restart: always

networks:
  default:
    external:
      name: nginx-proxy

 

Docker network 생성

Nginx-proxy container 구동전 docker network create commnad 를 이용하여 docker network 를 생성해야 합니다.

test@docker-test:~/web-service/nginx-proxy$ docker network create nginx-proxy
a5955ea1067f169fd1849ecd4c959c83319183dcb39188ddffe125423f9e5322
test@docker-test:~/web-service/nginx-proxy$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
e64ced1895e7        bridge              bridge              local
a2b1f4b8cfba        host                host                local
a5955ea1067f        nginx-proxy         bridge              local
bb45871e893c        none                null                local
test@docker-test:~/web-service/nginx-proxy$

 

 

WordPress container

blog1 docker-compose.yml 파일 생성

container 사용시 db가 저장될 디렉토리와 web 이 저장될 디렉토리를 생성 합니다.

test@docker-test:~/web-service$ mkdir blog1
test@docker-test:~/web-service$ cd blog1/
test@docker-test:~/web-service/blog1$ mkdir web-data
test@docker-test:~/web-service/blog1$ mkdir db-data
test@docker-test:~/web-service/blog1$ tree
.
├── db-data
└── web-data

 

docker-compose 파일 생성

도메인의 경우 test.com 을 Test dns-server 로 미리 준비해 놓았습니다.

test@docker-test:~/web-service/blog1$ vi docker-compose.yml
version: "3"

services:
  db:
     image: mariadb
     volumes:
       - ./db-data:/var/lib/mysql
     restart: always
     environment:
       MYSQL_ROOT_PASSWORD: test1234
       MYSQL_DATABASE: wordpress
       MYSQL_USER: wordpress
       MYSQL_PASSWORD: test1234
     container_name: wp_blog_db

  wordpress:
     image: wordpress:latest
     expose:
       - 80
     restart: always
     volumes:
       - ./web-data:/var/www/html
     environment:
       VIRTUAL_HOST: blog1.test.com
       WORDPRESS_DB_HOST: db:3306
       WORDPRESS_DB_USER: wordpress
       WORDPRESS_DB_PASSWORD: test1234
     container_name: wp_blog

networks:
  default:
    external:
      name: nginx-proxy

VIRTUAL_HOST 부분에 도메인을 설정해 줍니다. ex) blog1.test.com

 

Nginx-proxy 와 blog Wordprss 컨테이너를 구동 합니다.

Nginx-proxy 컨테이너 실행

test@docker-test:~/web-service$ cd ..
test@docker-test:~$ cd web-service/nginx-proxy/
test@docker-test:~/web-service/nginx-proxy$ docker-compose up -d --build
Pulling nginx-proxy (jwilder/nginx-proxy:latest)...
latest: Pulling from jwilder/nginx-proxy
e7bb522d92ff: Pull complete
6edc05228666: Pull complete
cd866a17e81f: Pull complete
d9f2d6a1f8f6: Pull complete
e9c7e986c8c1: Pull complete
a51bcd518fd9: Pull complete
66df98413ed2: Pull complete
aff8c6473b42: Pull complete
1c91fd608be1: Pull complete
7319453a5fbe: Pull complete
Digest: sha256:41506b2095779e6e64f34e26ccba35cb3668ee56a735cd740ac8c183af583294
Status: Downloaded newer image for jwilder/nginx-proxy:latest
Creating nginx-proxy ... done
test@docker-test:~/web-service/nginx-proxy$ docker ps
CONTAINER ID        IMAGE                 COMMAND                  CREATED             STATUS              PORTS                NAMES
2b9135ebe937        jwilder/nginx-proxy   "/app/docker-entrypo…"   4 seconds ago       Up 3 seconds        0.0.0.0:80->80/tcp   nginx-proxy
test@docker-test:~/web-service/nginx-proxy$

이제부터 시스템의 모든 80 Port 의 경우 Nginx-proxy 에서 받아 들이게 됩니다.

 

blog1 컨테이너 실행

test@docker-test:~$ cd web-service/blog1/
test@docker-test:~/web-service/blog1$ docker-compose up -d --build
Pulling wordpress (wordpress:latest)...
latest: Pulling from library/wordpress
8176e34d5d92: Pull complete
f6c81892adaa: Pull complete
c8125c73b868: Pull complete
5ef22f6299b6: Pull complete
8537460e9a8c: Pull complete
b837671b83f0: Pull complete
366ea9d8b411: Pull complete
c4dd539af472: Pull complete
445753fb3ee6: Pull complete
6811f6b5d500: Pull complete
2ca365cdc65d: Pull complete
c91023a57f04: Pull complete
dcf0735fda8a: Pull complete
6b23fdc3538b: Pull complete
2eed880b86fe: Pull complete
798b2e547e59: Pull complete
159be43511e4: Pull complete
b5605b08f665: Pull complete
20d8e9ec2764: Pull complete
Digest: sha256:670e4156377063df1a02f036354c52722de0348d46222ba30ef6a925c24cd46a
Status: Downloaded newer image for wordpress:latest
Pulling db (mariadb:latest)...
latest: Pulling from library/mariadb
4176fe04cefe: Pull complete
d1e86691d483: Pull complete
c3f621b14a80: Pull complete
7b3f1b17db07: Pull complete
add1151625d9: Pull complete
d40e879009a8: Pull complete
0f888e49f29b: Pull complete
bd51d7af1551: Pull complete
6cf37448a3b3: Pull complete
0519e00d29e5: Pull complete
8f83e3487101: Pull complete
Digest: sha256:d5f0bc88ba397233677ff75b7b1de693d5e84527ecf2b4f59adebf8d0bcac3c4
Status: Downloaded newer image for mariadb:latest
Creating wp_blog ... done
Creating wp_blog_db ...
test@docker-test:~/web-service/blog1$ docker ps
CONTAINER ID        IMAGE                 COMMAND                  CREATED             STATUS              PORTS                NAMES
e83e15350e05        wordpress:latest      "docker-entrypoint.s…"   4 seconds ago       Up 2 seconds        80/tcp               wp_blog
ce6d5afb2986        mariadb               "docker-entrypoint.s…"   4 seconds ago       Up 4 seconds        3306/tcp             wp_blog_db
2b9135ebe937        jwilder/nginx-proxy   "/app/docker-entrypo…"   3 minutes ago       Up 3 minutes        0.0.0.0:80->80/tcp   nginx-proxy
test@docker-test:~/web-service/blog1$

 

web browser  접속

http://blog1.test.com 으로 접속합니다.

blog1 컨테이너 구성이 끝났습니다. Wordprss 설정을 한후 blog2 컨테이너를 구성 합니다.

 

 

blog2 docker-compose.yml 파일 생성

test@docker-test:~$ cd web-service/
test@docker-test:~/web-service$ mkdir blog2
test@docker-test:~/web-service$ cd blog2
test@docker-test:~/web-service/blog2$ mkdir db-data
test@docker-test:~/web-service/blog2$ mkdir web-data
test@docker-test:~/web-service/blog2$ vi docker-compose.yml
version: "3"

services:
  db2:
     image: mariadb
     volumes:
       - ./db-data:/var/lib/mysql
     restart: always
     environment:
       MYSQL_ROOT_PASSWORD: test1234
       MYSQL_DATABASE: wordpress
       MYSQL_USER: wordpress
       MYSQL_PASSWORD: test1234
     container_name: wp_blog_db2

  wordpress2:
     image: wordpress:latest
     expose:
       - 80
     restart: always
     volumes:
       - ./web-data:/var/www/html
     environment:
       VIRTUAL_HOST: blog2.test.com
       WORDPRESS_DB_HOST: db2:3306
       WORDPRESS_DB_USER: wordpress
       WORDPRESS_DB_PASSWORD: test1234
     container_name: wp_blog2

networks:
  default:
    external:
      name: nginx-proxy

 

docker-compose.yml 파일 변경 사항

db -> db2

wp_blog_db ->  wp_blog_db2

wordpress -> wordpress2

VIRTUAL_HOST: blog2.test.com

WORDPRESS_DB_HOST: db2:3306

container_name: wp_blog2

 

blog2 컨테이너 실행

test@docker-test:~/web-service/blog2$ docker-compose up -d --build
Creating wp_blog2 ... done
Creating wp_blog2 ...
test@docker-test:~/web-service/blog2$ docker ps
CONTAINER ID        IMAGE                 COMMAND                  CREATED              STATUS              PORTS                NAMES
468a1f13cee1        wordpress:latest      "docker-entrypoint.s…"   About a minute ago   Up About a minute   80/tcp               wp_blog2
39d91c742082        mariadb               "docker-entrypoint.s…"   About a minute ago   Up About a minute   3306/tcp             wp_blog_db2
fa9442409280        mariadb               "docker-entrypoint.s…"   9 minutes ago        Up 9 minutes        3306/tcp             wp_blog_db
416704fdb038        wordpress:latest      "docker-entrypoint.s…"   9 minutes ago        Up 9 minutes        80/tcp               wp_blog
2b9135ebe937        jwilder/nginx-proxy   "/app/docker-entrypo…"   21 minutes ago       Up 21 minutes       0.0.0.0:80->80/tcp   nginx-proxy
test@docker-test:~/web-service/blog2$

 

 

web browser  접속

http://blog2.test.com 으로 접속합니다.

 

 

 

Docker Command 정리 #01

문서버전: 2018.02.20 v0.1

docker help 명령어 확인시 아래와 같은 명령어를 확인 할수 있습니다.

자주 사용하는 명령어 위주로 정리 하였습니다.

일부 내용의 오타가 있을수 있습니다. 🙂

옵션 부분의 경우 차후 정리할 예정입니다.

test@docker-test01:~$ docker help

Usage:  docker COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default "/home/test/.docker")
  -D, --debug              Enable debug mode
  -H, --host list          Daemon socket(s) to connect to
  -l, --log-level string   Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
      --tls                Use TLS; implied by --tlsverify
      --tlscacert string   Trust certs signed only by this CA (default "/home/test/.docker/ca.pem")
      --tlscert string     Path to TLS certificate file (default "/home/test/.docker/cert.pem")
      --tlskey string      Path to TLS key file (default "/home/test/.docker/key.pem")
      --tlsverify          Use TLS and verify the remote
  -v, --version            Print version information and quit

Management Commands:
  config      Manage Docker configs
  container   Manage containers
  image       Manage images
  network     Manage networks
  node        Manage Swarm nodes
  plugin      Manage plugins
  secret      Manage Docker secrets
  service     Manage services
  swarm       Manage Swarm
  system      Manage Docker
  volume      Manage volumes

Commands:
  attach      Attach local standard input, output, and error streams to a running container
  build       Build an image from a Dockerfile
  commit      Create a new image from a container's changes
  cp          Copy files/folders between a container and the local filesystem
  create      Create a new container
  diff        Inspect changes to files or directories on a container's filesystem
  events      Get real time events from the server
  exec        Run a command in a running container
  export      Export a container's filesystem as a tar archive
  history     Show the history of an image
  images      List images
  import      Import the contents from a tarball to create a filesystem image
  info        Display system-wide information
  inspect     Return low-level information on Docker objects
  kill        Kill one or more running containers
  load        Load an image from a tar archive or STDIN
  login       Log in to a Docker registry
  logout      Log out from a Docker registry
  logs        Fetch the logs of a container
  pause       Pause all processes within one or more containers
  port        List port mappings or a specific mapping for the container
  ps          List containers
  pull        Pull an image or a repository from a registry
  push        Push an image or a repository to a registry
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  rmi         Remove one or more images
  run         Run a command in a new container
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  search      Search the Docker Hub for images
  start       Start one or more stopped containers
  stats       Display a live stream of container(s) resource usage statistics
  stop        Stop one or more running containers
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
  top         Display the running processes of a container
  unpause     Unpause all processes within one or more containers
  update      Update configuration of one or more containers
  version     Show the Docker version information
  wait        Block until one or more containers stop, then print their exit codes

Run 'docker COMMAND --help' for more information on a command.
test@docker-test01:~$

 

docker help Command 정리

docker $command $option  형식으로 사용합니다.

docker attach

Attach local standard input, output, and error streams to a running container

official page doc: https://docs.docker.com/engine/reference/commandline/attach/#override-the-detach-sequence

docker attach test1

test@docker-test02:~$ docker run -d --name topdemo ubuntu /usr/bin/top -b
Unable to find image 'ubuntu:latest' locally
latest: Pulling from library/ubuntu
1be7f2b886e8: Pull complete
6fbc4a21b806: Pull complete
c71a6f8e1378: Pull complete
4be3072e5a37: Pull complete
06c6d2f59700: Pull complete
Digest: sha256:e27e9d7f7f28d67aa9e2d7540bdc2b33254b452ee8e60f388875e5b7d9b2b696
Status: Downloaded newer image for ubuntu:latest
ce15a2b8e919ab37b60113189f8c2547718fcbabeecce34224f3695b611e7bfe
test@docker-test02:~$


docker attach 실행 
test@docker-test02:~$ docker attach topdemo


top - 09:55:13 up  1:40,  0 users,  load average: 0.08, 0.05, 0.01
Tasks:   1 total,   1 running,   0 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.7 us,  0.7 sy,  0.0 ni, 98.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :   998340 total,   247164 free,   160772 used,   590404 buff/cache
KiB Swap:  1048572 total,  1042460 free,     6112 used.   638368 avail Mem

   PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
     1 root      20   0   36532   3064   2704 R   0.0  0.3   0:00.03 top

top - 09:55:16 up  1:40,  0 users,  load average: 0.08, 0.05, 0.01
Tasks:   1 total,   1 running,   0 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :   998340 total,   247164 free,   160772 used,   590404 buff/cache
KiB Swap:  1048572 total,  1042460 free,     6112 used.   638368 avail Mem

   PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
     1 root      20   0   36532   3064   2704 R   0.0  0.3   0:00.03 top

 

docker attach test2

test@docker-test02:~$ docker run --name ssh-server -d -p 12341:22 -v /home/test/ftp:/home/test/ftp ssh-server
test@docker-test02:~$ docker ps
CONTAINER ID        IMAGE               COMMAND               CREATED             STATUS              PORTS                   NAMES
210ec4045be4        ssh-server          "/usr/sbin/sshd -D"   2 hours ago         Up 2 seconds        0.0.0.0:12341->22/tcp   ssh-server
test@docker-test02:~$
test@docker-test02:~$ docker attach 210ec4045be4

docker attach 커맨드를 이용하여 ssh-server 컨테이너에 접속을 하였지만 접속이 안되는것처럼 보입니다.??

docker 명령어 입력마지막 부분에 /bin/bash 를 입력 하지 않을경우 위와같이 접속만 되어 있습니다.

Ctrl+\ 를 입력하여 attach를 종료 합니다.

종료후 아래와 같이 컨테이너가 종료 합니다.

test@docker-test02:~$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
test@docker-test02:~$

Ctrl+ p q 입력시 아래와 같이 컨테이너 실행상태에서 나올수 있습니다.

test@docker-test02:~/ssh-server$ docker attach ssh-server


read escape sequence
test@docker-test02:~/ssh-server$ docker ps
CONTAINER ID        IMAGE               COMMAND               CREATED             STATUS              PORTS                   NAMES
7576cad72333        ssh-server          "/usr/sbin/sshd -D"   2 minutes ago       Up 2 minutes        0.0.0.0:12341->22/tcp   ssh-server
test@docker-test02:~/ssh-server$

 

docker attach 로 컨테이너에 접속하기 위해서는 -d -it 옵션을 사용해야 합니다.

test@docker-test02:~$ docker run --name test -d -it debian
Unable to find image 'debian:latest' locally
latest: Pulling from library/debian
3e731ddb7fc9: Pull complete
Digest: sha256:4fcd8c0b6f5e3bd44a3e63be259fd0c038476d432953d449ef34aedf16def331
Status: Downloaded newer image for debian:latest
3fd41406c5968d8e3c5fd56903a23d6de4d88b230bdf69cff9b3e13ceb8fd213
test@docker-test02:~$ docker attach test
root@3fd41406c596:/#

-d 컨테이너를 생성하여 백그라운드에서 실행
-i 컨테이너 표준입력 열기
-t tty사용

 

docker build

Build an image from a Dockerfile

official page doc: https://docs.docker.com/engine/reference/commandline/build/

docker build test

test@docker-test02:~/nginx$ vi Dockerfile
test@docker-test02:~/nginx$ docker build --tag nginx .
~중략
test@docker-test02:~/nginx$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               latest              80889b2672a1        50 seconds ago      208MB

Dockerfile 작성후 image 생성시 사용 합니다.

–tag 옵션으로 image의 tag를 생성 할수 있습니다.

 

docker commit

Create a new image from a container’s changes

official page doc: https://docs.docker.com/engine/reference/commandline/commit/

docker commit test / git install

test@docker-test02:~/nginx$ docker ps
CONTAINER ID        IMAGE               COMMAND               CREATED             STATUS              PORTS                   NAMES
7576cad72333        ssh-server          "/usr/sbin/sshd -D"   32 minutes ago      Up 32 minutes       0.0.0.0:12341->22/tcp   ssh-server
test@docker-test02:~/nginx$ docker exec -it ssh-server /bin/bash
root@7576cad72333:/# apt-get install -y git
~중략
exit 를 입력한후 컨테이너에서 빠져 나옵니다.

test@docker-test02:~/nginx$ docker commit ssh-server ssh-server:git
sha256:64f7265d353e9a5a1fdb021c54205ffaae73ec0bd43a3f1cdf5cba510a3da93b
test@docker-test02:~/nginx$
test@docker-test02:~$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ssh-server          git                 64f7265d353e        44 seconds ago      281MB

 

docker run 으로 실행후 git 명령어 실행

test@docker-test02:~$ docker run -it -d ssh-server:git /bin/bash
5da63c65e0a36398a78a64d7199008c779ad20dd7cf31947fd776928475316ee
test@docker-test02:~$ docker exec -it ssh-server:git /bin/bash
Error: No such container: ssh-server:git
test@docker-test02:~$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
5da63c65e0a3        ssh-server:git      "/bin/bash"         24 seconds ago      Up 24 seconds       22/tcp              quirky_hamilton
test@docker-test02:~$ docker exec -it 5da63c65e0a3 /bin/bash
root@5da63c65e0a3:/# git
usage: git [--version] [--help] [-C <path>] [-c name=value]
           [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
           [-p | --paginate | --no-pager] [--no-replace-objects] [--bare]
           [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
           <command> [<args>]

These are common Git commands used in various situations:

start a working area (see also: git help tutorial)
   clone      Clone a repository into a new directory
   init       Create an empty Git repository or reinitialize an existing one

work on the current change (see also: git help everyday)
   add        Add file contents to the index
   mv         Move or rename a file, a directory, or a symlink
   reset      Reset current HEAD to the specified state
   rm         Remove files from the working tree and from the index

examine the history and state (see also: git help revisions)
   bisect     Use binary search to find the commit that introduced a bug
   grep       Print lines matching a pattern
   log        Show commit logs
   show       Show various types of objects

docker commit 의 경우 컨테이너의 변경 사항을 새로운 이미지로 만드는 작업 이라고 보시면 됩니다.

 

docker cp

Copy files/folders between a container and the local filesystem

official page doc: https://docs.docker.com/engine/reference/commandline/cp/

docker cp test

ex) docker cp $컨테이너이름:$경로 $host경로

test@docker-test:~/ftp-server$ docker cp ftpd:/etc/pure-ftpd/pureftpd.passwd /home/test/ftp-server/
test@docker-test:~/ftp-server$ ll
total 24
drwxrwxr-x 4 test test 4096 Feb 20 20:13 ./
drwxr-xr-x 4 test test 4096 Feb 19 21:43 ../
-rw-rw-r-- 1 test test  459 Feb 19 22:17 docker-compose.yml
drwxrwxr-x 2 test test 4096 Feb 19 22:41 pure-ftpd/
-rw-rw-r-- 1 test test   76 Feb 19 22:41 pureftpd.passwd
drwxrwxr-x 2 test test 4096 Feb 19 22:17 ssh-server/
test@docker-test:~/ftp-server$

docker cp의 경우 컨테이너의 파일을 카피 할때 사용 합니다.

 

docker create

Create a new container

official page doc: https://docs.docker.com/engine/reference/commandline/create/#specify-isolation-technology-for-container-isolation

docker create test

test@docker-test02:~/ssh-server$ docker create -i -t --name web-server httpd /bin/bash
Unable to find image 'httpd:latest' locally
latest: Pulling from library/httpd
4176fe04cefe: Pull complete
d6c01cf91b98: Pull complete
b7066921647a: Pull complete
643378aaba88: Pull complete
3c51f6dc6a3b: Pull complete
4f25e420c4cc: Pull complete
ccdbe37da15c: Pull complete
Digest: sha256:6e61d60e4142ea44e8e69b22f1e739d89e1dc8a2764182d7eecc83a5bb31181e
Status: Downloaded newer image for httpd:latest
c148af581e62e60f10bdf936953887c7c7bc8f812c1de722b7520550f5550ab2
test@docker-test02:~/ssh-server$
test@docker-test02:~/ssh-server$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ssh-server          git                 64f7265d353e        16 minutes ago      281MB
nginx               latest              80889b2672a1        38 minutes ago      208MB
ssh-server          latest              da649966e69c        About an hour ago   206MB
httpd               latest              01154c38b473        5 days ago          177MB

run 명령어의 경우 컨테이너를 만들고 실행하지만 create 의 경우 컨테이너 생성만 하며 실행하지 않습니다.

 

docker diff

Inspect changes to files or directories on a container’s filesystem

official page doc: https://docs.docker.com/engine/reference/commandline/diff/

docker diff test

test@docker-test01:~$ docker ps
CONTAINER ID        IMAGE               COMMAND               CREATED             STATUS              PORTS                   NAMES
4a9c504e3fc0        6aa9f4528408        "/usr/sbin/sshd -D"   3 hours ago         Up 3 hours          0.0.0.0:12341->22/tcp   ssh-server
test@docker-test01:~$ docker diff 4a9c504e3fc0
C /home/test
A /home/test/.cache
A /home/test/.cache/motd.legal-displayed
A /home/test/ftp
C /run
A /run/motd.dynamic
A /run/sshd.pid
C /run/utmp
C /var/log/lastlog
C /var/log/wtmp
test@docker-test01:~$

diff 명령어로 컨테이너에서 변경된 파일을 확인 할수 있습니다.

A 추가된 파일 / D 삭제된 파일 / C 변경된 파일

 

docker events

Get real time events from the server

official page doc: https://docs.docker.com/engine/reference/commandline/events/

docker events test

테스트를 위하여 2개의 터미널이 필요합니다.

터미널1 

test@docker-test01:~$ docker events

 

터미널2

test@docker-test01:~$ docker start ssh-server
ssh-server
test@docker-test01:~$

 

ssh-server 컨테이너 실행후

터미널1

test@docker-test01:~$ docker events


2018-02-20T20:29:20.559545172+09:00 network connect e6379e085e70251ff6d3aed56b526f0fac2d5cb35a62125ec35f9db043f88013 (container=4a9c504e3fc066c451c037b35041b1308e181b121cd54b3f2fea28b703c98276, name=bridge, type=bridge)
2018-02-20T20:29:20.825386119+09:00 container start 4a9c504e3fc066c451c037b35041b1308e181b121cd54b3f2fea28b703c98276 (image=ssh-server, name=ssh-server)

리얼타임으로 이벤트를 확인할수 있습니다.

 

docker exec

Run a command in a running container

official page doc: https://docs.docker.com/engine/reference/commandline/exec/

docker exec test

test@docker-test02:~$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
5da63c65e0a3        ssh-server:git      "/bin/bash"         31 minutes ago      Up 31 minutes       22/tcp              quirky_hamilton
test@docker-test02:~$ docker exec -it 5da63c65e0a3 /bin/bash
root@5da63c65e0a3:/#

docker exec는 실행중인 컨테이너에 접속할때 사용합니다.

 

docker export

Export a container’s filesystem as a tar archive

official page doc: https://docs.docker.com/engine/reference/commandline/export/

docker export test

test@docker-test02:~$ docker export ssh-server > ./ssh-server.tar
test@docker-test02:~$ ls
Dockerfile  ftp  nginx  ssh-server  ssh-server.tar
test@docker-test02:~$

컨테이너 백업시 사용합니다.

 

docker history

Show the history of an image

official page doc: https://docs.docker.com/engine/reference/commandline/history/

docker history test

test@docker-test01:~$ docker history ssh-server
IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
7497e5839808        4 hours ago         /usr/sbin/sshd -D                               293kB
6aa9f4528408        4 hours ago         /bin/sh -c #(nop)  CMD ["/usr/sbin/sshd" "-D…   0B
42ebcc23b6f4        4 hours ago         /bin/sh -c #(nop)  EXPOSE 22                    0B
6e1b50e948a4        4 hours ago         /bin/sh -c echo "export VISIBLE=now" >> /etc…   594B
6520e9fab9c9        4 hours ago         /bin/sh -c #(nop)  ENV NOTVISIBLE=in users p…   0B
559b0ee95543        4 hours ago         /bin/sh -c apt-get update && apt-get install…   94.6MB
f98d236d73eb        4 hours ago         /bin/sh -c #(nop)  MAINTAINER Sven Dowideit …   0B
0458a4468cbc        3 weeks ago         /bin/sh -c #(nop)  CMD ["/bin/bash"]            0B
<missing>           3 weeks ago         /bin/sh -c mkdir -p /run/systemd && echo 'do…   7B
<missing>           3 weeks ago         /bin/sh -c sed -i 's/^#\s*\(deb.*universe\)$…   2.76kB
<missing>           3 weeks ago         /bin/sh -c rm -rf /var/lib/apt/lists/*          0B
<missing>           3 weeks ago         /bin/sh -c set -xe   && echo '#!/bin/sh' > /…   745B
<missing>           3 weeks ago         /bin/sh -c #(nop) ADD file:a3344b835ea6fdc56…   112MB
test@docker-test01:~$

image history 를 출력합니다.

 

docker images

List images

official page doc: https://docs.docker.com/engine/reference/commandline/images/

docker images test

test@docker-test:~$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ftp/pure-ftpd       14.04               75c73f446597        22 hours ago        435MB
<none>              <none>              6a6688153895        23 hours ago        435MB
ssh-server          latest              1e5966c6bdf0        23 hours ago        206MB
ubuntu              16.04               0458a4468cbc        3 weeks ago         112MB
ubuntu              14.04               dc4491992653        3 weeks ago         222MB
test@docker-test:~$

docker image 정보를 출력합니다.

 

docker import

Import the contents from a tarball to create a filesystem image

official page doc: https://docs.docker.com/engine/reference/commandline/import/

docker import test

test@docker-test01:~$ cat ssh-server.tar | docker import - ssh-server
sha256:3f3f63beac844f0c2e806f2a4cc22457dd612abefd8417eabd9dbd1de5a92ecc
test@docker-test01:~$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ssh-server          latest              3f3f63beac84        2 seconds ago       253MB
test@docker-test01:~$

export 한 tar 파일로 images 를 생성 합니다.

 

docker info

Display system-wide information

official page doc: https://docs.docker.com/engine/reference/commandline/info/

docker info test

test@docker-test02:~$ docker info
Containers: 5
 Running: 1
 Paused: 0
 Stopped: 4
Images: 21
Server Version: 18.02.0-ce
Storage Driver: overlay2
 Backing Filesystem: extfs
 Supports d_type: true
 Native Overlay Diff: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: bridge host macvlan null overlay
 Log: awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: 9b55aab90508bd389d7654c4baf173a981477d55
runc version: 9f9c96235cc97674e935002fc3d78361b696a69e
init version: 949e6fa
Security Options:
 apparmor
 seccomp
  Profile: default
Kernel Version: 4.4.0-62-generic
Operating System: Ubuntu 16.04.3 LTS
OSType: linux
Architecture: x86_64
CPUs: 2
Total Memory: 974.9MiB
Name: docker-test02
ID: QAGI:PK3E:CG7L:3D73:UQJ3:UP4P:LZTZ:2PZP:3GBS:ORWS:FL36:EWWJ
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Labels:
Experimental: false
Insecure Registries:
 127.0.0.0/8
Live Restore Enabled: false

WARNING: No swap limit support
test@docker-test02:~$

docker 정보를 출력 합니다.

 

docker inspect

Return low-level information on Docker objects

official page doc: https://docs.docker.com/engine/reference/commandline/inspect/

docker inspect test

test@docker-test01:~$ docker inspect ssh-server
[
    {
        "Id": "sha256:3f3f63beac844f0c2e806f2a4cc22457dd612abefd8417eabd9dbd1de5a92ecc",
        "RepoTags": [
            "ssh-server:latest"
        ],
        "RepoDigests": [],
        "Parent": "",
        "Comment": "Imported from -",
        "Created": "2018-02-20T11:52:52.28045397Z",
        "Container": "",
        "ContainerConfig": {
            "Hostname": "",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": null,
            "Cmd": null,
            "Image": "",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": null
        },
        "DockerVersion": "18.02.0-ce",
        "Author": "",
        "Config": {
            "Hostname": "",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": null,
            "Cmd": null,
            "Image": "",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": null
        },
        "Architecture": "amd64",
        "Os": "linux",
        "Size": 253405442,
        "VirtualSize": 253405442,
        "GraphDriver": {
            "Data": {
                "MergedDir": "/var/lib/docker/overlay2/6c47d31e2d5ff00a9fb4676f595a33fd45afaa6592c50cb069d1777df6bd4616/merged",
                "UpperDir": "/var/lib/docker/overlay2/6c47d31e2d5ff00a9fb4676f595a33fd45afaa6592c50cb069d1777df6bd4616/diff",
                "WorkDir": "/var/lib/docker/overlay2/6c47d31e2d5ff00a9fb4676f595a33fd45afaa6592c50cb069d1777df6bd4616/work"
            },
            "Name": "overlay2"
        },
        "RootFS": {
            "Type": "layers",
            "Layers": [
                "sha256:3f277380640a29287b45210df57c9c6ea7711a363a593128e9c0c2fec50b91b8"
            ]
        },
        "Metadata": {
            "LastTagTime": "2018-02-20T20:52:52.283195652+09:00"
        }
    }
]
test@docker-test01:~$

image 정보 확인시 사용합니다.

이미지ID / 생성일 / Docker 버전 / 이미지 생성자 / CPU 확인할수 있습니다.

 

docker kill

Kill one or more running containers

official page doc: https://docs.docker.com/engine/reference/commandline/kill/

docker kill test2

test@docker-test:~$ docker ps
CONTAINER ID        IMAGE                 COMMAND                  CREATED             STATUS              PORTS                                                      NAMES
74a223f30014        ftp/pure-ftpd:14.04   "/bin/sh -c '/usr/sb…"   About an hour ago   Up About an hour    0.0.0.0:21->21/tcp, 0.0.0.0:20000-20099->20000-20099/tcp   ftpd
b76d16b5f4b4        ssh-server            "/usr/sbin/sshd -D"      About an hour ago   Up About an hour    0.0.0.0:12341->22/tcp                                      ssh-server
test@docker-test:~$ docker kill ssh-server
ssh-server
test@docker-test:~$ docker ps
CONTAINER ID        IMAGE                 COMMAND                  CREATED             STATUS              PORTS                                                      NAMES
74a223f30014        ftp/pure-ftpd:14.04   "/bin/sh -c '/usr/sb…"   About an hour ago   Up About an hour    0.0.0.0:21->21/tcp, 0.0.0.0:20000-20099->20000-20099/tcp   ftpd
test@docker-test:~$

 

docker kill test2

test@docker-test:~/ftp-server$ docker kill ftpd ssh-server
ftpd
ssh-server
test@docker-test:~/ftp-server$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
test@docker-test:~/ftp-server$

docker kill 명령어로 컨테이너에 kill 시그널을 보낼수 있습니다.

하나 또는 하나이상의 컨테이를 kill 시킬수 있습니다.

 

docker load

Load an image from a tar archive or STDIN

official page doc: https://docs.docker.com/engine/reference/commandline/load/

docker load test

test@docker-test02:~$ docker load -i ssh-server.tar
3f277380640a: Loading layer [==================================================>]  264.1MB/264.1MB
Loaded image: ssh-server:latest
test@docker-test02:~$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ssh-server          latest              3f3f63beac84        26 minutes ago      253MB
test@docker-test02:~$

tar -> docker image로 변환 합니다.?

 

docker login

Log in to a Docker registry

official page doc: https://docs.docker.com/engine/reference/commandline/login/

//차후테스트

docker 저장소에 로그인합니다.

 

docker logout

Log out from a Docker registry

official page doc: https://docs.docker.com/engine/reference/commandline/logout/

//차후테스트

docker 저장소에서 로그아웃합니다.

 

docker logs

Fetch the logs of a container

official page doc: https://docs.docker.com/engine/reference/commandline/logs/

//차후테스트

컨테이너 로그를 출력합니다.

 

docker pause

Pause all processes within one or more containers

official page doc: https://docs.docker.com/engine/reference/commandline/pause/

docker pause test

test@docker-test01:~/ssh-server$ docker ps
CONTAINER ID        IMAGE               COMMAND               CREATED             STATUS              PORTS                   NAMES
d2269ec836fd        ssh-server          "/usr/sbin/sshd -D"   3 minutes ago       Up 3 minutes        0.0.0.0:12341->22/tcp   ssh-server
test@docker-test01:~/ssh-server$ docker pause ssh-server
ssh-server
test@docker-test01:~/ssh-server$ docker ps
CONTAINER ID        IMAGE               COMMAND               CREATED             STATUS                  PORTS                   NAMES
d2269ec836fd        ssh-server          "/usr/sbin/sshd -D"   6 minutes ago       Up 6 minutes (Paused)   0.0.0.0:12341->22/tcp   ssh-server
test@docker-test01:~/ssh-server$

컨테이너 내의 모든 프로세스 일시정지

 

docker port

List port mappings or a specific mapping for the container

official page doc: https://docs.docker.com/engine/reference/commandline/port/

docker port test

test@docker-test01:~/ssh-server$ docker port ssh-server
22/tcp -> 0.0.0.0:12341
test@docker-test01:~/ssh-server$

특정컨테이너의 port 연결 정보를 확인 합니다.

 

docker ps

List containers

official page doc: https://docs.docker.com/engine/reference/commandline/ps/

docker ps test

test@docker-test01:~/ssh-server$ docker ps
CONTAINER ID        IMAGE               COMMAND               CREATED             STATUS              PORTS                   NAMES
d2269ec836fd        ssh-server          "/usr/sbin/sshd -D"   12 minutes ago      Up 12 minutes       0.0.0.0:12341->22/tcp   ssh-server
test@docker-test01:~/ssh-server$

컨테이너 정보를 확인 합니다.

 

docker pull

Pull an image or a repository from a registry

official page doc: https://docs.docker.com/engine/reference/commandline/pull/

docker pull test

test@docker-test01:~$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ssh-server          latest              f1c017c1bfcf        34 minutes ago      206MB
ubuntu              16.04               0458a4468cbc        3 weeks ago         112MB
test@docker-test01:~$ docker pull ubuntu:latest
latest: Pulling from library/ubuntu
Digest: sha256:e27e9d7f7f28d67aa9e2d7540bdc2b33254b452ee8e60f388875e5b7d9b2b696
Status: Downloaded newer image for ubuntu:latest
test@docker-test01:~$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ssh-server          latest              f1c017c1bfcf        34 minutes ago      206MB
ubuntu              16.04               0458a4468cbc        3 weeks ago         112MB
ubuntu              latest              0458a4468cbc        3 weeks ago         112MB
test@docker-test01:~$

images 저장소에서 image를 down 합니다.

 

docker push

Push an image or a repository to a registry

official page doc: https://docs.docker.com/engine/reference/commandline/push/

docker push test

//차후테스트

docker hub 에 이미지를 등록합니다.

 

docker rename

Rename a container

official page doc: https://docs.docker.com/engine/reference/commandline/rename/

docker rename test

test@docker-test01:~$ docker ps
CONTAINER ID        IMAGE               COMMAND               CREATED             STATUS              PORTS                   NAMES
d2269ec836fd        ssh-server          "/usr/sbin/sshd -D"   23 minutes ago      Up 23 minutes       0.0.0.0:12341->22/tcp   ssh-server
test@docker-test01:~$ docker rename ssh-server sshd
test@docker-test01:~$ docker ps
CONTAINER ID        IMAGE               COMMAND               CREATED             STATUS              PORTS                   NAMES
d2269ec836fd        ssh-server          "/usr/sbin/sshd -D"   23 minutes ago      Up 23 minutes       0.0.0.0:12341->22/tcp   sshd
test@docker-test01:~$

컨테이너의 이름을 변경 합니다.

 

docker restart

Restart one or more containers

official page doc: https://docs.docker.com/engine/reference/commandline/restart/

docker restart test

test@docker-test01:~$ docker restart sshd
sshd
test@docker-test01:~$ docker ps
CONTAINER ID        IMAGE               COMMAND               CREATED             STATUS              PORTS                   NAMES
d2269ec836fd        ssh-server          "/usr/sbin/sshd -D"   25 minutes ago      Up 3 seconds        0.0.0.0:12341->22/tcp   sshd
test@docker-test01:~$

컨테이너를 재시작 합니다.

 

docker rm

Remove one or more containers

official page doc: https://docs.docker.com/engine/reference/commandline/rm/

docker rm test

test@docker-test01:~$ docker stop sshd
sshd
test@docker-test01:~$ docker rm sshd
sshd
test@docker-test01:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
test@docker-test01:~$

컨테이너를 삭제 합니다.

 

docker rmi

Remove one or more images

official page doc: https://docs.docker.com/engine/reference/commandline/rmi/

docker rmi test

test@docker-test01:~$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu              latest              0458a4468cbc        3 weeks ago         112MB
test@docker-test01:~$ docker rmi 0458a4468cbc
Untagged: ubuntu:latest
Untagged: ubuntu@sha256:e27e9d7f7f28d67aa9e2d7540bdc2b33254b452ee8e60f388875e5b7d9b2b696
Deleted: sha256:0458a4468cbceea0c304de953305b059803f67693bad463dcbe7cce2c91ba670
Deleted: sha256:77e6ddba346d8ad1e436256f6373dede5af4002006981b7d4116c561c759cefa
Deleted: sha256:8db758ab2fdb54da0aec53aeac876934337e6170f5a8c8872b3d4171e3d465b7
Deleted: sha256:a7fc6b405fe8ef71edfa6163d1dc9f1cb1df426049eefaa7d388e9df21a061ad
Deleted: sha256:5a3e35538f7f2e2727c8ac92f08c30002b9e8a77737de0dab91244344d59f69b
Deleted: sha256:ff986b10a018b48074e6d3a68b39aad8ccc002cdad912d4148c0f92b3729323e
test@docker-test01:~$

images 를 삭제 합니다.

 

docker run

Run a command in a new container

official page doc: https://docs.docker.com/engine/reference/run/

docker run test

test@docker-test02:~/ssh-server$ docker run --name ssh-server -d -p 12341:22 -v /home/test/ftp:/home/test/ftp ssh-server
eef4f1176e28dca616b2b4ba7a3b59c6722f8a7f8a3d079c901b31c8a00f60ba
test@docker-test02:~/ssh-server$

컨테이너를 실행 합니다.

 

docker save

Save one or more images to a tar archive (streamed to STDOUT by default)

official page doc: https://docs.docker.com/engine/reference/commandline/save/

docker save test

test@docker-test01:~$ docker save -o ssh-server.tar ssh-server
test@docker-test01:~$ ls
ftp  ssh-server  ssh-server.tar
test@docker-test01:~$

docker images 를 tar 파일로 저장합니다.

 

docker search

Search the Docker Hub for images

official page doc: https://docs.docker.com/engine/reference/commandline/search/

docker search test

test@docker-test01:~$ docker search nginx
NAME                                                   DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
nginx                                                  Official build of Nginx.                        7971                [OK]
jwilder/nginx-proxy                                    Automated Nginx reverse proxy for docker con…   1276                                    [OK]
richarvey/nginx-php-fpm                                Container running Nginx + PHP-FPM capable of…   517                                     [OK]
jrcs/letsencrypt-nginx-proxy-companion                 LetsEncrypt container to use with nginx as p…   312                                     [OK]
kong                                                   Open-source Microservice & API Management la…   158                 [OK]
webdevops/php-nginx                                    Nginx with PHP-FPM                              97                                      [OK]
kitematic/hello-world-nginx                            A light-weight nginx container that demonstr…   95
bitnami/nginx                                          Bitnami nginx Docker Image                      44                                      [OK]
zabbix/zabbix-web-nginx-mysql                          Zabbix frontend based on Nginx web-server wi…   43                                      [OK]
linuxserver/nginx                                      An Nginx container, brought to you by LinuxS…   33
1and1internet/ubuntu-16-nginx-php-phpmyadmin-mysql-5   ubuntu-16-nginx-php-phpmyadmin-mysql-5          26                                      [OK]
tobi312/rpi-nginx                                      NGINX on Raspberry Pi / armhf                   17                                      [OK]
wodby/drupal-nginx                                     Nginx for Drupal container image                9                                       [OK]
webdevops/nginx                                        Nginx container                                 8                                       [OK]
blacklabelops/nginx                                    Dockerized Nginx Reverse Proxy Server.          8                                       [OK]
nginxdemos/nginx-ingress                               NGINX Ingress Controller for Kubernetes         8
centos/nginx-18-centos7                                Platform for running nginx 1.8 or building n…   6
1science/nginx                                         Nginx Docker images that include Consul Temp…   4                                       [OK]
nginxdemos/hello                                       NGINX webserver that serves a simple page co…   3                                       [OK]
pebbletech/nginx-proxy                                 nginx-proxy sets up a container running ngin…   2                                       [OK]
behance/docker-nginx                                   Provides base OS, patches and stable nginx f…   2                                       [OK]
centos/nginx-112-centos7                               Platform for running nginx 1.12 or building …   2
travix/nginx                                           NGinx reverse proxy                             1                                       [OK]
toccoag/openshift-nginx                                Nginx reverse proxy for Nice running on same…   1                                       [OK]
mailu/nginx                                            Mailu nginx frontend                            0                                       [OK]
test@docker-test01:~$

Docker 이미지를 검색 합니다.

 

docker start

Start one or more stopped containers

official page doc: https://docs.docker.com/engine/reference/commandline/start/

docker start test

test@docker-test02:~/ssh-server$ docker ps -a
CONTAINER ID        IMAGE               COMMAND               CREATED             STATUS                     PORTS               NAMES
eef4f1176e28        ssh-server          "/usr/sbin/sshd -D"   16 minutes ago      Exited (0) 3 seconds ago                       ssh-server
test@docker-test02:~/ssh-server$ docker start ssh-server
ssh-server
test@docker-test02:~/ssh-server$

정지된 컨테이너를 실행 합니다.

 

docker stats

Display a live stream of container(s) resource usage statistics

official page doc: https://docs.docker.com/engine/reference/commandline/stats/

docker stats test

test@docker-test02:~/ssh-server$ docker stats ssh-server

CONTAINER ID        NAME                CPU %               MEM USAGE / LIMIT   MEM %               NET I/O             BLOCK I/O           PIDS
eef4f1176e28        ssh-server          0.00%               716KiB / 974.9MiB   0.07%               648B / 0B           0B / 0B             1

컨테이너의 자원 사용량을 확인 합니다.

 

 

docker stop

Stop one or more running containers

official page doc: https://docs.docker.com/engine/reference/commandline/stop/

docker stop test

test@docker-test02:~/ssh-server$ docker ps
CONTAINER ID        IMAGE               COMMAND               CREATED             STATUS              PORTS                   NAMES
eef4f1176e28        ssh-server          "/usr/sbin/sshd -D"   20 minutes ago      Up 4 minutes        0.0.0.0:12341->22/tcp   ssh-server
test@docker-test02:~/ssh-server$ docker stop ssh-server
ssh-server
test@docker-test02:~/ssh-server$

컨테이너를 정지합니다.

 

 

 

 

docker tag

Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE

official page doc: https://docs.docker.com/engine/reference/commandline/tag/

docker tag test

test@docker-test02:~/ssh-server$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ssh-server          latest              8ee8efce9736        40 minutes ago      206MB
<none>              <none>              3f3f63beac84        2 hours ago         253MB
ubuntu              16.04               0458a4468cbc        3 weeks ago         112MB
test@docker-test02:~/ssh-server$ docker tag 0458a4468cbc nginx-test
test@docker-test02:~/ssh-server$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ssh-server          latest              8ee8efce9736        41 minutes ago      206MB
<none>              <none>              3f3f63beac84        2 hours ago         253MB
ubuntu              16.04               0458a4468cbc        3 weeks ago         112MB
nginx-test          latest              0458a4468cbc        3 weeks ago         112MB
test@docker-test02:~/ssh-server$

test@docker-test02:~/ssh-server$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ssh-server          latest              8ee8efce9736        45 minutes ago      206MB
<none>              <none>              3f3f63beac84        2 hours ago         253MB
nginx-test          0.1                 0458a4468cbc        3 weeks ago         112MB
nginx-test          latest              0458a4468cbc        3 weeks ago         112MB
ubuntu              16.04               0458a4468cbc        3 weeks ago         112MB
test@docker-test02:~/ssh-server$

 

 

docker top

Display the running processes of a container

official page doc: https://docs.docker.com/engine/reference/commandline/top/

docker top test

test@docker-test02:~/ssh-server$ docker top ssh-server
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                17478               17460               0                   23:23               ?                   00:00:00            /usr/sbin/sshd -D
test@docker-test02:~/ssh-server$

컨테이너의 실행중인 프로세스를 표시합니다.

 

 

docker unpause

Unpause all processes within one or more containers

official page doc: https://docs.docker.com/engine/reference/commandline/unpause/

docker unpause test

test@docker-test02:~/ssh-server$ docker ps
CONTAINER ID        IMAGE               COMMAND               CREATED             STATUS                  PORTS                   NAMES
eef4f1176e28        ssh-server          "/usr/sbin/sshd -D"   About an hour ago   Up 2 minutes (Paused)   0.0.0.0:12341->22/tcp   ssh-server
test@docker-test02:~/ssh-server$ docker unpause ssh-server
ssh-server
test@docker-test02:~/ssh-server$ docker ps
CONTAINER ID        IMAGE               COMMAND               CREATED             STATUS              PORTS                   NAMES
eef4f1176e28        ssh-server          "/usr/sbin/sshd -D"   About an hour ago   Up 2 minutes        0.0.0.0:12341->22/tcp   ssh-server
test@docker-test02:~/ssh-server$

docker pause 상태에서 복귀 합니다.

 

 

docker update

Update configuration of one or more containers

official page doc: https://docs.docker.com/engine/reference/commandline/update/

docker update test

//차후테스트

컨테이너 설정을 업데이트 합니다.

 

 

docker version

Show the Docker version information

official page doc: https://docs.docker.com/engine/reference/commandline/version/

docker version test

test@docker-test01:~$ docker version
Client:
 Version:       18.02.0-ce
 API version:   1.36
 Go version:    go1.9.3
 Git commit:    fc4de44
 Built: Wed Feb  7 21:16:33 2018
 OS/Arch:       linux/amd64
 Experimental:  false
 Orchestrator:  swarm

Server:
 Engine:
  Version:      18.02.0-ce
  API version:  1.36 (minimum version 1.12)
  Go version:   go1.9.3
  Git commit:   fc4de44
  Built:        Wed Feb  7 21:15:05 2018
  OS/Arch:      linux/amd64
  Experimental: false
test@docker-test01:~$

docker version 을 출력합니다.

 

docker wait

Block until one or more containers stop, then print their exit codes

official page doc: https://docs.docker.com/engine/reference/commandline/wait/

docker wait test

터미널 1

test@docker-test02:~/ssh-server$ docker wait ssh-server

docker wait ssh-server 명령어를 실행후 대기합니다.

 

터미널2 

test@docker-test02:~$ docker kill ssh-server
ssh-server

 

터미널1 

test@docker-test02:~/ssh-server$ docker wait ssh-server
137
test@docker-test02:~/ssh-server$

docker wait 실행시 컨테이너가 종료할때까지 대기하다가 종료 코드를 출력 합니다.

 

 

 

 

Container Backup and Recovery

컨테이너를 tar 파일로 저장

 

Container Backup

docker-test01 Server 에서 ssh-server.tar 파일 생성

test@docker-test01:~$ docker ps
CONTAINER ID        IMAGE               COMMAND               CREATED             STATUS              PORTS                   NAMES
4a9c504e3fc0        ssh-server          "/usr/sbin/sshd -D"   8 minutes ago       Up About a minute   0.0.0.0:12341->22/tcp   ssh-server
test@docker-test01:~$

docker commit 
test@docker-test01:~$ docker commit -p 4a9c504e3fc0 ssh-server
sha256:7497e5839808a3d16aa4e665250b0b56c2c2b68316389583a8dc5b3a369a0e1d
test@docker-test01:~$

docker save
test@docker-test01:~$ docker save -o ssh-server.tar ssh-server

 

Container Recovery

docker-test02 Server 에서 docker load 명령어를 이용하여 ssh-server.tar 파일을 load

test@docker-test02:~/ssh-server$ docker load -i ssh-server.tar
ff986b10a018: Loading layer  115.7MB/115.7MB
9c7183e0ea88: Loading layer  15.87kB/15.87kB
c98ef191df4b: Loading layer  14.85kB/14.85kB
92914665e7f6: Loading layer  5.632kB/5.632kB
6f4ce6b88849: Loading layer  3.072kB/3.072kB
45c63a717468: Loading layer  98.94MB/98.94MB
6a99d630753a: Loading layer  3.072kB/3.072kB
4974e070de92: Loading layer  302.1kB/302.1kB
Loaded image: ssh-server:latest
test@docker-test02:~/ssh-server$
image 확인
test@docker-test02:~/ssh-server$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ssh-server          latest              7497e5839808        11 minutes ago      207MB
test@docker-test02:~/ssh-server$

 

ssh-server 실행

test@docker-test02:~/ssh-server$ mkdir ~/ftp
test@docker-test02:~/ssh-server$ docker run --name ssh-server -d -p 12341:22 -v /home/test/ftp:/home/test/ftp ssh-server
210ec4045be4be565689aebcb00d5d7171f954efdb1bf493563a7669a74b7400
test@docker-test02:~/ssh-server$ docker ps
CONTAINER ID        IMAGE               COMMAND               CREATED             STATUS              PORTS                   NAMES
210ec4045be4        ssh-server          "/usr/sbin/sshd -D"   3 seconds ago       Up 2 seconds        0.0.0.0:12341->22/tcp   ssh-server
test@docker-test02:~/ssh-server$

 

 

docker-compose pure-ftpd ssh-server 구성

 

참고사항:

pure-ftpd ubuntu 14.04

ssh-server ubuntu 16.04

vmware NAT 환경시 문제가 생길수 있습니다. Bridge 환경으로 테스트 하시기 바랍니다.

 

Github

test@docker-test:~$ git clone https://github.com/visualwork/Docker-test.git

/Docker-test/test04 에 있습니다. 🙂

 

디렉토리 구조

ftp-server$ tree

├── docker-compose.yml
├── pure-ftpd
│       ├── Dockerfile
│       └── pureftpd.passwd
└── ssh-server
    └── Dockerfile

 

docker-compose 를 구성하기 위하여 디렉토리를 생성 합니다. 

test@docker-test:~$ mkdir ftp-server
test@docker-test:~$ cd ftp-server/
test@docker-test:~/ftp-server$ mkdir pure-ftpd
test@docker-test:~/ftp-server$ mkdir ssh-server
test@docker-test:~/ftp-server$ sudo mkdir /ftp-data
test@docker-test:~/ftp-server$ sudo chown test:test /ftp-data/

 

docker-compose.yml 파일 생성

test@docker-test:~/ftp-server$ pwd
/home/test/ftp-server
test@docker-test:~/ftp-server$ vi docker-compose.yml

version: '3'

services:
  pure-ftpd:
    build:
      context: pure-ftpd
    image: ftp/pure-ftpd:14.04
    container_name: ftpd
    ports:
      - "21:21"
      - "20000-20099:20000-20099"
    volumes:
      - "/ftp-data:/home/ftp"
    restart: always

  ssh-server:
    build:
      context: ssh-server
    image: ssh-server
    container_name: ssh-server
    ports:
      - "12341:22"
    volumes:
      - "/ftp-data:/home/test/ftp:ro"
    restart: always

 

 

ssh-server Dockerfile 생성

test@docker-test:~/ftp-server$ cd ssh-server/
test@docker-test:~/ftp-server/ssh-server$ vi Dockerfile
FROM ubuntu:16.04
MAINTAINER Sven Dowideit <SvenDowideit@docker.com>
 
#RUN apt-get update && apt-get install -y openssh-server
RUN apt-get update && apt-get install -y openssh-server \
&& mkdir /var/run/sshd \
&& useradd -ms /bin/bash test \
&& sed -ie 's/test:!/test:\$6\$pIPlIFrg\$WZRTmOoouwD6L\/IDgz8fw97agQjdeXticOJyayjUYwmiuNKkJE92rBtr0XDXhVE4rSi9PkWv8rtnA0rCuR6ts\//g' /etc/shadow \
&& sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config \
&& sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
 
#COPY data/* /.ROOT/
 
ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile
 
EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]

test user 의 패스워드는 test1234 입니다.

 

pure-ftpd Dockerfile 생성

FROM ubuntu:14.04

MAINTAINER test@test

RUN apt-get update && \
apt-get install pure-ftpd openssl libpam-dev libcap2-dev libldap2-dev libmysqlclient-dev libmysqlclient15-dev libpq-dev libssl-dev po-debconf dpkg-dev debhelper -y

RUN mkdir /tmp/pure-ftpd/ && \
        cd /tmp/pure-ftpd/ && \
        apt-get source pure-ftpd && \
        cd pure-ftpd-* && \
        sed -i '/^optflags=/ s/$/ --without-capabilities/g' ./debian/rules && \
        dpkg-buildpackage -b -uc
RUN dpkg -i /tmp/pure-ftpd/pure-ftpd-common*.deb
RUN apt-get -y install openbsd-inetd
RUN dpkg -i /tmp/pure-ftpd/pure-ftpd_*.deb
RUN apt-mark hold pure-ftpd pure-ftpd-common
RUN cd /etc/pure-ftpd && \
adduser ftpd-data && \
mkdir /home/ftp && \
chown ftpd-data:ftpd-data -R /home/ftp && \
echo yes > ./conf/ChrootEveryone && \
echo yes > ./conf/DontResolve && \
echo yes > ./conf/NoChmod && \
echo yes > ./conf/ProhibitDotFilesWrite && \
echo yes > ./conf/CustomerProof && \
echo '20000 20099' > ./conf/PassivePortRange && \
echo ',21' > ./conf/Bind && \
echo '2' > ./conf/TLS && \
openssl req -x509 -nodes -days 1825 -newkey rsa:2048 -keyout /etc/ssl/private/pure-ftpd.pem -out /etc/ssl/private/pure-ftpd.pem -subj "/C=KR/ST=SouthKorea/L=Seoul/O=test.com/OU=IT Department/CN=ftp.test.com"
ADD pureftpd.passwd /etc/pure-ftpd/
RUN pure-pw mkdb
RUN ln -sf /dev/stdout /var/log/pure-ftpd/transfer.log
CMD /usr/sbin/pure-ftpd -l puredb:/etc/pure-ftpd/pureftpd.pdb -x -u 30 -H -S ,21 -O clf:/var/log/pure-ftpd/transfer.log -Z -A -p 20000:20099 -E -R -8 UTF-8 -Y 2
EXPOSE 21/tcp 20000-20099/tcp

 

pureftpd.passwd file 생성

test@docker-test:~/ftp-server/pure-ftpd$ pwd
/home/test/ftp-server/pure-ftpd
test@docker-test:~/ftp-server/pure-ftpd$ vi pureftpd.passwd
test:$1$P4DB31/0$iIPf8.YJ6XP6k1zsmQtJq1:1000:1000::/home/ftp/./::::::::::::

(pure-ftpd VirtualUser 생성시 pureftpd.passwd 파일에 계정을 추가 하면 됩니다.)

test / test1234 입니다.

 

ftp-server 실행

test@docker-test:~/ftp-server$ docker-compose up -d --build
test@docker-test:~/ftp-server$ docker ps
CONTAINER ID        IMAGE                 COMMAND                  CREATED             STATUS              PORTS                                                      NAMES
25725255d655        ftp/pure-ftpd:14.04   "/bin/sh -c '/usr/sb…"   8 seconds ago       Up 6 seconds        0.0.0.0:21->21/tcp, 0.0.0.0:20000-20099->20000-20099/tcp   ftpd
b319c9a53cb3        ssh-server            "/usr/sbin/sshd -D"      8 seconds ago       Up 6 seconds        0.0.0.0:12341->22/tcp                                      ssh-server
test@docker-test:~/ftp-server$

 

pure-ftp user 생성시 참고

test@docker-test:~/ftp-server$ docker ps
CONTAINER ID        IMAGE                 COMMAND                  CREATED             STATUS              PORTS                                                      NAMES
6906ee88690b        ftp/pure-ftpd:14.04   "/bin/sh -c '/usr/sb…"   37 seconds ago      Up 35 seconds       0.0.0.0:21->21/tcp, 0.0.0.0:20000-20099->20000-20099/tcp   ftpd
c48bb291d39e        ssh-server            "/usr/sbin/sshd -D"      37 seconds ago      Up 35 seconds       0.0.0.0:12341->22/tcp                                      ssh-server
test@docker-test:~/ftp-server$ docker exec -it 6906ee88690b /bin/bash

root@6906ee88690b:/# pure-pw useradd test1 -u ftpd-data -g ftpd-data -d /home/ftp
Password:
Enter it again:
root@6906ee88690b:/# pure-pw mkdb


root@6906ee88690b:/# cat /etc/pure-ftpd/pureftpd.passwd
test:$1$P4DB31/0$iIPf8.YJ6XP6k1zsmQtJq1:1000:1000::/home/ftp/./::::::::::::
test1:$1$R4VNLgS0$Upx3H9Fky0V/LJ9uNALim.:1000:1000::/home/ftp/./::::::::::::

 

pureftpd.passwd 파일에 user:password 필드로 입력하면 됩니다.

컨테이너의  /etc/pure-ftpd/pureftpd.passwd 파일에서 패스워드를 확인 가능 합니다.

test@docker-test:~/ftp-server/pure-ftpd$ cat pureftpd.passwd
test:$1$P4DB31/0$iIPf8.YJ6XP6k1zsmQtJq1:1000:1000::/home/ftp/./::::::::::::

 

 

filezilla 접속테스트

 

별도로 Test는 진행하지 않았지만 sshfs 로 mount 를 할수 있습니다.

ssh-server port 12341 로 mount 하여 사용할수 있습니다. 🙂

 

 

 

 

dockerfile 을 이용한 ssh-server 를 테스트

ftp 운영시 sshfs 로 mount 를 할때 유용 합니다.

 

Github

test@docker-test:~$ git clone https://github.com/visualwork/Docker-test.git

/Docker-test/test03 에 있습니다. 🙂

 

디렉토리 생성 및 Dockerfile 작성

test@docker-test:~$ mkdir ssh-server
test@docker-test:~$ cd ssh-server/
test@docker-test:~/ssh-server$ vi Dockerfile


FROM ubuntu:16.04
MAINTAINER Sven Dowideit <SvenDowideit@docker.com>

#RUN apt-get update && apt-get install -y openssh-server
RUN apt-get update && apt-get install -y openssh-server \
&& mkdir /var/run/sshd \
&& useradd -ms /bin/bash test \
&& sed -ie 's/test:!/test:\$6\$pIPlIFrg\$WZRTmOoouwD6L\/IDgz8fw97agQjdeXticOJyayjUYwmiuNKkJE92rBtr0XDXhVE4rSi9PkWv8rtnA0rCuR6ts\//g' /etc/shadow \
&& sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config \
&& sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd

#COPY data/* /.ROOT/

ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile

EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]

linux 이미지는 16.04 이용합니다.

openssh-server 설치후 user 를 생성 합니다.

username은 test 입니다.

test password 의 경우 sed -ie 로 미리지정된 password 로 변경 합니다.

test 유저의 password 는 test1234 입니다.

 

 

 

dockerfile build

test@docker-test:~/ssh-server$ docker build --tag ssh-server .
Sending build context to Docker daemon 2.56kB
Step 1/7 : FROM ubuntu:16.04
16.04: Pulling from library/ubuntu
1be7f2b886e8: Pull complete
6fbc4a21b806: Pull complete
c71a6f8e1378: Pull complete
4be3072e5a37: Pull complete
06c6d2f59700: Pull complete
Digest: sha256:e27e9d7f7f28d67aa9e2d7540bdc2b33254b452ee8e60f388875e5b7d9b2b696
Status: Downloaded newer image for ubuntu:16.04
---> 0458a4468cbc
Step 2/7 : MAINTAINER Sven Dowideit <SvenDowideit@docker.com>
---> Running in 6d0f296e4098
Removing intermediate container 6d0f296e4098
---> 03402fb21291
Step 3/7 : RUN apt-get update &
~중략

 

image 확인

test@docker-test:~/ssh-server$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
ssh-server latest bb93ba239129 4 minutes ago 206MB
ubuntu 16.04 0458a4468cbc 3 weeks ago 112MB
test@docker-test:~/ssh-server$

test@docker-test:~/ssh-server$ mkdir ~/ftp

 

컨테이너 실행

컨테이너 실행전 /home/test 디렉토리에 ftp 디렉토리를 생성합니다.
test@docker-test:~/ssh-server$ mkdir ~/ftp
test@docker-test:~/ssh-server$ docker run --name ssh-server -d -p 12341:22 -v /home/test/ftp:/home/test/ftp ssh-server
b8b8a4cba5f21f54b93071383ae05b0b9b0d7c4ae64da0ba94bb8b6479f1ca3d
test@docker-test:~/ssh-server$

/home/test/ftp 디렉토리의 경우 ftp 볼륨연결시 sshfs 연결 목적으로 사용합니다.

 

컨테이너 실행확인

test@docker-test:~/ssh-server$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b8b8a4cba5f2 ssh-server "/usr/sbin/sshd -D" 8 seconds ago Up 8 seconds 0.0.0.0:12341->22/tcp ssh-server

 

 Volume 연결 테스트

test@docker-test:~$ cd ftp/
test@docker-test:~/ftp$ ls
test@docker-test:~/ftp$ touch 0
test@docker-test:~/ftp$ cd
test@docker-test:~$ docker ps
CONTAINER ID        IMAGE               COMMAND               CREATED             STATUS              PORTS                   NAMES
b8b8a4cba5f2        ssh-server          "/usr/sbin/sshd -D"   6 minutes ago       Up 6 minutes        0.0.0.0:12341->22/tcp   ssh-server
test@docker-test:~$ docker exec -it b8b8a4cba5f2 /bin/bash
root@b8b8a4cba5f2:/# cd /home/test/ftp/
root@b8b8a4cba5f2:/home/test/ftp# ls
0

 

ssh 접속 테스트 (port를 12341 로 접속해야 합니다.)

login as: test
test@192.168.192.134's password:
Welcome to Ubuntu 16.04.3 LTS (GNU/Linux 4.4.0-62-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

test@ce4578c8c06b:~$