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:~$

 

 

docker-compose

Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration. To learn more about all the features of Compose, see the list of features.

 

참고페이지: https://docs.docker.com/compose/https://docs.docker.com/compose/overview/

docker-compose 란?  간단히 설명하면 YAML 방식 설정파일을 이용하여 여러 컨테이너를 설치? 하고 운영 하는툴로 보시면 됩니다.

 

Github

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

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

 

docker-compose 설치

test@ubuntu1604:~$ 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
test@ubuntu1604:~$ sudo chmod +x /usr/local/bin/docker-compose
test@tomomo:~$ docker-compose --version
docker-compose version 1.11.2, build dfed245
test@tomomo:~$

 

 

docker-compose 를 이용하여 web-service 를 테스트 합니다.

(Nginx + php71 + mysql57)

Docker-compose 디렉토리 구조

sanjuk@ubuntu1604:~/web-service$ tree
.
├── docker-compose.yml
├── nginx
│   └── conf
│       └── default.conf
└── php
    ├── conf
    │   └── php.ini
    └── Dockerfile

4 directories, 4 files
sanjuk@ubuntu1604:~/web-service$

 

docker-compose.yml 파일 

위치: /home/sanjuk/web-service

version: '2'

services:
    mysql:
        image: mysql:5.7
        ports:
            - 3306:3306
        volumes:
            - ./mysql:/var/lib/mysql
        restart: always
        environment:
            MYSQL_ROOT_PASSWORD: root
            MYSQL_USER: docker
            MYSQL_PASSWORD: docker
            MYSQL_DATABASE: docker

    nginx:
        image: nginx:1.10.2
        ports:
            - 80:80
        restart: always
        volumes:
            - ./nginx/conf:/etc/nginx/conf.d
            - ~/Projects:/code
        links:
            - php
        depends_on:
            - php

    php:
        build: php
        expose:
            - 9000
        restart: always
        volumes:
            - ./php/conf/php.ini:/usr/local/etc/php/conf.d/custom.ini
            - ~/Projects:/code
        links:
            - mysql

 

version : compose file format 참고페이지 https://docs.docker.com/compose/compose-file/#reference-and-guidelines

services: 컨테이너 별로 만들어 주면 됩니다. ex) nginx , apache , mariadb , mysql 등

mysql 필드 설명

image: mysql:5.7 version 을 사용합니다.

ports: 3306:3306  / host의 3306 포트와 컨테이너의 3306 포트를 연결 합니다.

volumes: /mysql:/var/lib/mysql 내부 디렉토리 와 컨테이너 디렉토리를 연결 합니다.

restart: always  리부팅시에도 자동으로 실행을 합니다.

environment: 환경변수 설정?
MYSQL_ROOT_PASSWORD: root  /  mysql root 패스워드
MYSQL_USER: docker                   / mysql user 생성
MYSQL_PASSWORD: docker        / user password 생성
MYSQL_DATABASE: docker          / user database 생성

nginx 필드 설명

links: – php / php 컨테이너와 연결을 합니다.

depends_on: 서비스와 시작순서간의 종속성 설정?

The depends_on option can be used in place of links to indicate dependencies between services and startup order

참고페이지: https://docs.docker.com/compose/compose-file/compose-versioning/#version-2

 

php 필드 설명

build: php  / Dockerfile 을 통하여 build 시 build 라는 필드를 입력합니다.

expose: 9000 : 외부로 연결하지 않고 다른 컨테이너에서만 액세스 할수 있습니다.

Expose ports without publishing them to the host machine – they’ll only be accessible to linked services. Only the internal port can be specified.

참고페이지: https://docs.docker.com/compose/compose-file/compose-file-v2/

links: mysql 컨테이너와 연결

Link to containers in another service. Either specify both the service name and a link alias (“SERVICE:ALIAS”), or just the service name.

 

nginx default.conf 파일 생성

위치: /home/sanjuk/web-service/nginx/conf

server {
    listen       80 default_server;
    server_name  localhost _;
    index        index.php index.html index.htm;
    root         /code;

    location / {
        try_files   $uri $uri/ /index.php?$query_string;
        autoindex on;
    }

    location ~ \.php$ {
        try_files $uri /index.php =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass php:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

 

php/Dockerfile 생성

위치 : /home/sanjuk/web-service/php

FROM php:7.1-fpm

RUN apt-get update

# Some basic extensions
RUN docker-php-ext-install -j$(nproc) json mbstring opcache pdo pdo_mysql mysqli

# Curl
RUN apt-get install -y libcurl4-openssl-dev
RUN docker-php-ext-install -j$(nproc) curl

# GD
RUN apt-get install -y libpng-dev libjpeg-dev
RUN docker-php-ext-install -j$(nproc) gd

# Intl
RUN apt-get install -y libicu-dev
RUN docker-php-ext-install -j$(nproc) intl

 

php.ini 생성

위치 /home/sanjuk/web-service/php/conf

display_errors = On
display_startup_errors = On
default_charset = "UTF-8"
html_errors = On
date.timezone = Asia/Seoul

 

docker-compose 실행

실행위치

sanjuk@ubuntu1604:~/web-service$ pwd
/home/sanjuk/web-service
sanjuk@ubuntu1604:~/web-service$ ls
docker-compose.yml  nginx  php
sanjuk@ubuntu1604:~/web-service$

 

실행

sanjuk@ubuntu1604:~/web-service$ docker-compose up -d --build

(web-service 디렉토리에서 실행을 하며 docker-compose.yml 파일이 있어야 합니다.)

 

컨테이너 동작 확인

sanjuk@ubuntu1604:~/web-service$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED              STATUS              PORTS                         NAMES
b94d040597dd        nginx:1.10.2        "nginx -g 'daemon of…"   About a minute ago   Up 38 seconds       0.0.0.0:80->80/tcp, 443/tcp   webservice_nginx_1
2738120d80de        webservice_php      "docker-php-entrypoi…"   About a minute ago   Up 39 seconds       9000/tcp                      webservice_php_1
efeb60c666f9        mysql:5.7           "docker-entrypoint.s…"   About a minute ago   Up 39 seconds       0.0.0.0:3306->3306/tcp        webservice_mysql_1
sanjuk@ubuntu1604:~/web-service$

 

info.php 파일생성

sanjuk@ubuntu1604:~$ sudo chown sanjuk:sanjuk Projects/
sanjuk@ubuntu1604:~$ sudo vi Projects/info.php
<?php phpinfo(); ?>

 

webbrowser확인

 

 

Dockerfile 작성

아래 내용은 테스트 예제 이며 실제 Web-server 운영시는 docker-compose 를 많이 사용합니다.

단독 서비스를 운영하지 않는다면 Service 를 apache + mariadb 로 컨테이너를 나눠서 관리하는게

좀더 편하게 관리 할수 있습니다.

 

Github

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

/Docker-test/test01 에 Dockerfile 이 있습니다. 🙂

 

 

Dockerfile 을 작성 nginx Dockerfile 예제

nginx 디렉토리 생성후 Dockerfile 을 작성 합니다.

test@ubuntu1604:~$ mkdir nginx
test@ubuntu1604:~$ cd nginx/
test@ubuntu1604:~$ mkdir data
test@ubuntu1604:~/nginx$ vi Dockerfile

FROM ubuntu:16.04
MAINTAINER sanjuk <test@anonymouse.com>

RUN apt-get update
RUN apt-get install -y nginx
RUN echo "\ndaemon off;" >> /etc/nginx/nginx.conf
RUN chown -R www-data:www-data /var/lib/nginx


VOLUME /data

WORKDIR /etc/nginx

CMD ["nginx"]

EXPOSE 80
EXPOSE 443

 

FROM: 배포판 이미지

MAINTAINER : 메인테이너 정보

RUN : 스크립트 실행 또는 명령어 실행

VOLUME : 호스트와 공유할 디렉토리 정보 (컨테이너의 볼륨과 호스트 디렉토리 연결로 보시면 됩니다.)

CMD : 컨테이너 시작시 실행할 스크립트 또는 명령어

EXPOSE 호스트와 연결할 포트

 

build 명령으로 이미지 생성

test@ubuntu1604:~/nginx$ docker build --tag nginx-web01 .
Sending build context to Docker daemon  2.048kB
Step 1/11 : FROM ubuntu:16.04
16.04: Pulling from library/ubuntu
3b37166ec614: Already exists
504facff238f: Already exists
ebbcacd28e10: Already exists
c7fb3351ecad: Already exists
2e3debadcbf7: Already exists
Digest: sha256:45ddfa61744947b0b8f7f20b8de70cbcdd441a6a0532f791fd4c09f5e491a8eb
Status: Downloaded newer image for ubuntu:16.04
 ---> b9e15a5d1e1a
Step 2/11 : MAINTAINER sanjuk <test@anonymouse.com>
 ---> Running in d1dc8cb42cec
Removing intermediate container d1dc8cb42cec
 ---> 31d7669ef650
Step 3/11 : RUN apt-get update
 ---> Running in 058f47b0073a
Get:1 http://archive.ubuntu.com/ubuntu xenial InRelease [247 kB]
Get:2 http://security.ubuntu.com/ubuntu xenial-security InRelease [107 kB]
Get:3 http://security.ubuntu.com/ubuntu xenial-security/universe Sources [95.4 kB]
~중략

 

image 확인

test@ubuntu1604:~/nginx$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx-web01         latest              fae98fcdce37        2 minutes ago       212MB
ubuntu              16.04               b9e15a5d1e1a        3 weeks ago         115MB
test@ubuntu1604:~/nginx$

 

docker 실행

test@ubuntu1604:~/nginx$ docker run --name web-service -d -p 80:80 -v /root/nginx/data:/data nginx-web01
a56208a8b4e04b800ee523353f2a31b7c1be79ac19689410214070df9fbea6e8
test@ubuntu1604:~/nginx$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                         NAMES
a56208a8b4e0        nginx-web01         "nginx"             3 seconds ago       Up 2 seconds        0.0.0.0:80->80/tcp, 443/tcp   web-service
test@ubuntu1604:~/nginx$

 

webbrowser 확인

 

nginx 컨테이너 접속

test@ubuntu1604:~/nginx$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                         NAMES
f03a5bb4f756        nginx:latest        "nginx"             12 minutes ago      Up 12 minutes       0.0.0.0:80->80/tcp, 443/tcp   hello-nginx
test@ubuntu1604:~/nginx$
test@ubuntu1604:~/nginx$ docker exec -it f03a5bb4f756 /bin/bash
root@f03a5bb4f756:/etc/nginx#

 

Install Docker CE from binaries

링크: https://docs.docker.com/install/linux/docker-ce/binaries/

 

테스트 : ubuntu1604 vm

Docker 바이너리 압축파일 Down

https://download.docker.com/linux/static/stable/x86_64/

Index of /linux/static/stable/x86_64/
../
docker-17.03.0-ce.tgz  2017-03-01 11:11  27M
docker-17.03.1-ce.tgz  2017-03-28 04:46  27M
docker-17.03.2-ce.tgz  2017-06-28 03:35  27M
docker-17.06.0-ce.tgz  2017-06-28 05:17  29M
docker-17.06.1-ce.tgz  2017-08-18 02:35  29M
docker-17.06.2-ce.tgz  2017-09-05 10:39  29M
docker-17.09.0-ce.tgz  2017-09-27 01:47  29M
docker-17.09.1-ce.tgz  2017-12-08 12:22  29M
docker-17.12.0-ce.tgz  2017-12-27 09:52  33M

 

wget down

test@ubuntu1604:~$ wget https://download.docker.com/linux/static/stable/x86_64/docker-17.12.0-ce.tgz
--2018-02-05 18:21:58--  https://download.docker.com/linux/static/stable/x86_64/docker-17.12.0-ce.tgz
Resolving download.docker.com (download.docker.com)... 54.192.183.142, 54.192.183.217, 54.192.183.121, ...
Connecting to download.docker.com (download.docker.com)|54.192.183.142|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 34272897 (33M) [application/x-tar]
Saving to: ‘docker-17.12.0-ce.tgz’

docker-17.12.0-ce.t 100%[===================>]  32.68M  13.4MB/s    in 2.4s

2018-02-05 18:22:01 (13.4 MB/s) - ‘docker-17.12.0-ce.tgz’ saved [34272897/34272897]

test@ubuntu1604:~$

 

압축풀기

test@ubuntu1604:~$ tar xvf docker-17.12.0-ce.tgz
docker/
docker/docker-containerd-shim
docker/docker-containerd
docker/docker-runc
docker/docker
docker/docker-init
docker/docker-containerd-ctr
docker/docker-proxy
docker/dockerd
test@ubuntu1604:~$

 

docker 파일 copy 

test@ubuntu1604:~$ sudo cp docker/* /usr/bin/

 

Docker test

test@ubuntu1604:~$ sudo dockerd &
~중략
test@ubuntu1604:~$ sudo docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED                                                                                                                                                                                                            STATUS              PORTS               NAMES
test@ubuntu1604:~$

 

docker 사용자 등록

test@ubuntu1604:~$ sudo usermod -aG docker test

 

 

systemd Scripts 생성

docker.service

sanjuk@docker-test:~$ cat /lib/systemd/system/docker.service
[Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com
After=network-online.target docker.socket firewalld.service
Wants=network-online.target
Requires=docker.socket

[Service]
Type=notify
# the default is not to use systemd for cgroups because the delegate issues still
# exists and systemd currently does not support the cgroup feature set required
# for containers run by docker
ExecStart=/usr/bin/dockerd -H fd://
ExecReload=/bin/kill -s HUP $MAINPID
LimitNOFILE=1048576
# Having non-zero Limit*s causes performance problems due to accounting overhead
# in the kernel. We recommend using cgroups to do container-local accounting.
LimitNPROC=infinity
LimitCORE=infinity
# Uncomment TasksMax if your systemd version supports it.
# Only systemd 226 and above support this version.
TasksMax=infinity
TimeoutStartSec=0
# set delegate yes so that systemd does not reset the cgroups of docker containers
Delegate=yes
# kill only the docker process, not all processes in the cgroup
KillMode=process
# restart the docker process if it exits prematurely
Restart=on-failure
StartLimitBurst=3
StartLimitInterval=60s

[Install]
WantedBy=multi-user.target

 

docker.socket

sanjuk@docker-test:~$ vi /lib/systemd/system/docker.socket
[Unit]
Description=Docker Socket for the API
PartOf=docker.service

[Socket]
ListenStream=/var/run/docker.sock
SocketMode=0660
SocketUser=root
SocketGroup=docker

[Install]
WantedBy=sockets.target

 

systemctl docker enable 

test@ubuntu1604:~$ sudo -i
[sudo] password for test:
root@ubuntu1604:~# docker ps
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
root@ubuntu1604:~# systemctl enable docker
Created symlink from /etc/systemd/system/multi-user.target.wants/docker.service to /lib/systemd/system/docker.service.
root@ubuntu1604:~# init 6

 

docker Test

ubuntu16.04 컨테이너 실행 및 컨테이너 접속

sanjuk@ubuntu1604:~$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
sanjuk@ubuntu1604:~$ docker run ubuntu:16.04
Unable to find image 'ubuntu:16.04' locally
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
sanjuk@ubuntu1604:~$ docker run --rm -it ubuntu:16.04 /bin/bash
root@cd21ecd3c368:/# uname -a
Linux cd21ecd3c368 4.4.0-62-generic #83-Ubuntu SMP Wed Jan 18 14:10:15 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
root@cd21ecd3c368:/# exit

 

 

 

Docker install

# Docker EE 와 CE 차이

– Docker Enterprise Edition / Docker Community Edition

 

# Docker install

Ubuntu 16.04

test@docker-test:~$ curl -s https://get.docker.com/ | sudo sh

 

CentOS7

# yum install -y yum-utils device-mapper-persistent-data lvm2
# yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
# yum install docker-ce
# systemctl enable docker
# systemctl start docker

 

 

# sudo 없이 사용하기

docker는 기본적으로 root권한이 필요합니다. root가 아닌 사용자가 sudo없이 사용하려면 해당 사용자를 docker그룹에 추가합니다.

sudo usermod -aG docker $USER # 현재 접속중인 사용자에게 권한주기

test@docker-test:~$ sudo usermod -aG docker test

사용자가 로그인 중이라면 다시 로그인 후 권한이 적용됩니다.

# Docker Version 확인

test@docker-test:~$ docker version
Client:
 Version:      17.03.0-ce
 API version:  1.26
 Go version:   go1.7.5
 Git commit:   60ccb22
 Built:        Thu Feb 23 11:02:43 2017
 OS/Arch:      linux/amd64

Server:
 Version:      17.03.0-ce
 API version:  1.26 (minimum version 1.12)
 Go version:   go1.7.5
 Git commit:   60ccb22
 Built:        Thu Feb 23 11:02:43 2017
 OS/Arch:      linux/amd64
 Experimental: false
test@docker-test:~$

 

# Container 실행

docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...]

옵션 설명

-d : detached mode 흔히 말하는 백그라운드 모드
-p : 호스트와 컨테이너의 포트를 연결 (포워딩)
-v : 호스트와 컨테이너의 디렉토리를 연결 (마운트)
-e : 컨테이너 내에서 사용할 환경변수 설정
-name : 컨테이너 이름 설정
-rm : 프로세스 종료시 컨테이너 자동제거
-it : -i 와 -t 를 동시에 사용한것으로 터미널 입력을 위한 옵션
-link : 컨테이너 연결 [컨테이너명:별칭]

 

# Ubuntu 16.04 Container 생성

test@docker-test:~$ docker run ubuntu:16.04
Unable to find image 'ubuntu:16.04' locally
16.04: Pulling from library/ubuntu
d54efb8db41d: Pull complete
f8b845f45a87: Pull complete
e8db7bf7c39f: Pull complete
9654c40e9079: Pull complete
6d9ef359eaaa: Pull complete
Digest: sha256:dd7808d8792c9841d0b460122f1acf0a2dd1f56404f8d1e56298048885e45535
Status: Downloaded newer image for ubuntu:16.04
test@docker-test:~$

 

# Ubuntu 16.04 컨테이너 실행 및 컨테이너 접속

test@docker-test:~$ docker run --rm -it ubuntu:16.04 /bin/bash
root@ecc3042c5486:/# ls
bin   dev  home  lib64  mnt  proc  run   srv  tmp  var
boot  etc  lib   media  opt  root  sbin  sys  usr
root@ecc3042c5486:/# cat /etc/issue
Ubuntu 16.04.2 LTS \n \l

root@ecc3042c5486:/# uname -a
Linux ecc3042c5486 4.4.0-62-generic #83-Ubuntu SMP Wed Jan 18 14:10:15 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
root@ecc3042c5486:/#

컨테이너 내부에 들어가기 위해 bash쉘을 실행 키보드 입력을 위해 -it 옵션을 사용
접속을 종료 하면 컨테이너가 자동으로 삭제 되도록 –rm 옵션을 추가합니다.

 

# apache Container 생성

-p 옵션을 사용하여 외부와 내부 80 포트를 연결 합니다.

–name 옵션을 사용하여 httpd-test 로 컨테이너 name 을 지정 합니다.

test@docker-test:~$ docker run -d -p 80:80 --name httpd-test httpd
Unable to find image 'httpd:latest' locally
latest: Pulling from library/httpd
f2b6b4884fc8: Pull complete
b58fe2a5c9f1: Pull complete
e797fea70c45: Pull complete
6c7b4723e810: Pull complete
02074013c987: Pull complete
a4a11b801d86: Pull complete
70d17a98bee0: Pull complete
Digest: sha256:8359424a58cf59f1ea6a1a55e3974d5d569a510ebec0004357cf200adce5f27a
Status: Downloaded newer image for httpd:latest
a88a9dbfe728a3d9a9ea1c209b6773eb24d7de63a16de97519d2acab5d762650
test@docker-test:~$

 

컨테이너 확인

test@docker-test:~$ docker ps
CONTAINER ID        IMAGE               COMMAND              CREATED              STATUS              PORTS                NAMES
a88a9dbfe728        httpd               "httpd-foreground"   About a minute ago   Up About a minute   0.0.0.0:80->80/tcp   httpd-test
test@docker-test:~$

 

접속 확인

 

컨테이너 정지시 docker stop $Container_id 를 사용합니다.

test@docker-test:~$ docker ps
CONTAINER ID        IMAGE               COMMAND              CREATED             STATUS              PORTS                NAMES
a88a9dbfe728        httpd               "httpd-foreground"   7 minutes ago       Up 6 minutes        0.0.0.0:80->80/tcp   httpd-test
test@docker-test:~$ docker stop a88a9dbfe728
a88a9dbfe728
test@docker-test:~$

 

컨테이너 재사용시 docker ps -a 으로 확인후

docker start $Container_id 를 하시면 됩니다.

test@docker-test:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND              CREATED             STATUS                      PORTS               NAMES
a88a9dbfe728        httpd               "httpd-foreground"   8 minutes ago       Exited (0) 18 seconds ago                       httpd-test
test@docker-test:~$ docker start a88a9dbfe728
a88a9dbfe728
test@docker-test:~$

 

컨테이너 삭제시 docker rm 을 사용합니다.

test@docker-test:~$ docker rm a88a9dbfe728
a88a9dbfe728

 

docker run 으로 image 에서 만든 컨테이너만 삭제 되며 해당 이미지는 남아 있습니다.

test@docker-test:~$ docker images |grep -i httpd
httpd                 latest              e2a1033f4f86        2 hours ago         178MB
test@docker-test:~$

 

# MySQL5.7 Container 생성

test@docker-test:~$ docker run -d -p 3306:3306 -e MYSQL_ALLOW_EMPTY_PASSWORD=true --name mysql mysql:5.7
Unable to find image 'mysql:5.7' locally
5.7: Pulling from library/mysql
693502eb7dfb: Already exists
08d0e9d74b1b: Pull complete
e700ebfbe6bc: Pull complete
f718f1976629: Pull complete
575a0830e278: Pull complete
8461dfcf361d: Pull complete
349434898dfb: Pull complete
78d351522443: Pull complete
21897ab46952: Pull complete
ca6ffbbedc10: Pull complete
ba8ff064032b: Pull complete
Digest: sha256:6d4b33d189d62afe590ee4b35f92aae31ffa79ccc4d4db8bd3d3b893c8019596
Status: Downloaded newer image for mysql:5.7
f33c70888d81987a40957ea0f65fcf108d6a15248a25c139eebcf60ac6de4474
test@docker-test:~$

 

Host OS 에서 접속 테스트

test@docker-test:~$ mysql -h127.0.0.1 -uroot
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.17 MySQL Community Server (GPL)

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

mysql> quit
Bye
test@docker-test:~$

 

# mariadb Container

docker search mariadb 명령어로 배포중인 mariadb 컨테이너를 확인 할수 있습니다.

공식 image 의 경우 OFFICIAL [OK] 를 확인 할수 있습니다.

test@ubuntu1604:~$ docker search mariadb
NAME                                   DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mariadb                                MariaDB is a community-developed fork of M...   1462      [OK]
bitnami/mariadb                        Bitnami MariaDB Docker Image                    40                   [OK]
paintedfox/mariadb                     A docker image for running MariaDB 5.5, a ...   29                   [OK]
toughiq/mariadb-cluster                Dockerized Automated MariaDB Galera Cluste...   19                   [OK]
linuxserver/mariadb                    A Mariadb container, brought to you by Lin...   18
million12/mariadb                      MariaDB 10 on CentOS-7 with UTF8 defaults       14                   [OK]
webhippie/mariadb                      Docker images for mariadb                       10                   [OK]
colinmollenhour/mariadb-galera-swarm   MariaDb w/ Galera Cluster, DNS-based servi...   9                    [OK]
monitoringartist/zabbix-db-mariadb     Docker image of MariaDB optimized for Zabbix    8                    [OK]
panubo/mariadb-galera                  MariaDB Galera Cluster                          8                    [OK]
wodby/mariadb-alpine                   mariadb-alpine                                  5                    [OK]
wodby/drupal-mariadb                   MariaDB for Drupal                              4                    [OK]
tianon/mariadb                         DEPRECATED; use mariadb:* -- ♪ "I just met...   4                    [OK]
tutum/mariadb                          Base docker image to run a MariaDB databas...   3
lsioarmhf/mariadb                      ARMHF based Linuxserver.io image of mariadb     2
juanluisbaptiste/otrs-mariadb          Preconfigured MariaDB database for OTRS         1                    [OK]
wodby/mariadb                                                                          1                    [OK]
drupaldocker/mariadb                   MariaDB for Drupal                              1                    [OK]
needo/mariadb                                                                          1                    [OK]
jkleczkowski/mariadb                   You can change server charset and collatio...   0                    [OK]
benyoo/mariadb                         Alpine MariaDb run in docker                    0                    [OK]
centos/mariadb-101-centos7             MariaDB 10.1 SQL Database Server Docker image   0
whatwedo/mariadb                                                                       0                    [OK]
kitpages/mariadb-galera                MariaDB with Galera                             0                    [OK]
gjchen/mariadb                         Alpine Linux with MariaDB configured.           0                    [OK]
test@ubuntu1604:~$

 

mariadb 이미지 다운

mariadb:latest 의 경우 마지막 버전을 의미합니다.

test@ubuntu1604:~$ docker pull mariadb:latest
latest: Pulling from library/mariadb
ad74af05f5a2: Pull complete
0639788facc8: Pull complete
de70fa77eb2b: Pull complete
724179e94999: Pull complete
57fbc7ff5cf1: Pull complete
9d5794cf4e5c: Pull complete
b29a1331369b: Pull complete
66ad135be9a5: Pull complete
bb60a21b125b: Pull complete
8313b6b444b9: Pull complete
5891f0cb9ab8: Pull complete
55b71a694f6c: Pull complete
Digest: sha256:8ea33570152349b827d7121b88dc3f44a64e1cc7646cfae01faee4824b9b0007
Status: Downloaded newer image for mariadb:latest
test@ubuntu1604:~$

 

mariadb 컨테이너을 실행 합니다.

port 3306 으로 맵핑 하고 password 를 my-secret-pw 로 지정 하였습니다.

test@ubuntu1604:~$ docker run --name mariadb -p 3306:3306 -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mariadb:latest
(MYSQL_ROOT_PASSWORD= mariadb root password 입니다.)

test@ubuntu1604:~$ docker ps
CONTAINER ID        IMAGE                    COMMAND                  CREATED             STATUS              PORTS                                                      NAMES
5e66b8ea5c14        mariadb:latest           "docker-entrypoint..."   4 seconds ago       Up 4 seconds        0.0.0.0:3306->3306/tcp                                     mariadb
c8c1c38656cb        sanbsd/pure-ftpd:14.04   "/bin/sh -c '/usr/..."   18 hours ago        Up 36 minutes       0.0.0.0:21->21/tcp, 0.0.0.0:20000-20099->20000-20099/tcp   ftpd
331d935c6000        ssh-server               "/usr/sbin/sshd -D"      18 hours ago        Up 36 minutes       0.0.0.0:22222->22/tcp                                      ssh-server

 

Host 에서 mariadb 접속 테스트

-p 3306:3306 으로 맵핑 되어 있기 때문 -h 127.0.0.1 로 접속 할수 있습니다.

test@ubuntu1604:~$ mysql -h127.0.0.1 -uroot -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 14
Server version: 10.2.7-MariaDB-10.2.7+maria~jessie mariadb.org binary distribution

Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> status;
--------------
mysql  Ver 15.1 Distrib 10.0.29-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2

Connection id:          14
Current database:
Current user:           root@172.17.0.1
SSL:                    Not in use
Current pager:          stdout
Using outfile:          ''
Using delimiter:        ;
Server:                 MariaDB
Server version:         10.2.7-MariaDB-10.2.7+maria~jessie mariadb.org binary distribution
Protocol version:       10
Connection:             127.0.0.1 via TCP/IP
Server characterset:    latin1
Db     characterset:    latin1
Client characterset:    utf8
Conn.  characterset:    utf8
TCP port:               3306
Uptime:                 14 min 11 sec

Threads: 7  Questions: 48  Slow queries: 0  Opens: 36  Flush tables: 1  Open tables: 30  Queries per second avg: 0.056
--------------

MariaDB [(none)]>