[docker 버전 : 1.12]


docker 를 빌드할 때, Dockerfile로 생성하는 단계가 있다. 


docker build -t google-sandbox -f Dockerfile .



docker history 커맨드를 보면, image 안에 여러 image id가 존재하는 것을 볼 수 있다. 즉 RUN 지시자로 정의된 항목마다 하나의 image id가 존재하는 것을 볼 수 있다.


$ docker history 9ee4b3d0f0b5

IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
9ee4b3d0f0b5        3 minutes ago       /bin/sh -c #(nop)  ENTRYPOINT ["/docker-entry   0 B
17e114f16e50        3 minutes ago       /bin/sh -c #(nop)  VOLUME [/data /log]          0 B
18e87f892df1        3 minutes ago       /bin/sh -c #(nop)  ENV TERM=xterm               0 B
df973dbe65e4        3 minutes ago       /bin/sh -c #(nop) COPY file:0939c051875b38702   30 B

ba77ab6a5bd4        8 minutes ago       /bin/sh -c cd /tmp && rm -rf *                  0 B

...




또한 docker push 할 때, image id 단위로 push되는 것을 볼 수 있다.




docker 이미지의 내부 구조를 살펴보면, read-only이면서 순차적인 layer로 구성되어 있다.

특히 docker 1.10부터는 암호화된 hash, 충돌이 나지 않는 hash key로 image id를 구성한다고 한다.




이런 구조의 장점은 기존 이미지의 재활용을 잘 한다는 점이다.

도커를 테스트해보니. 딱 필요한(수정한) 부분만 image id가 생성된다. 따라서 디스크 용량 이슈가 확실히 적어진다.

그래서 컨테이너도 효율적으로 관리할 수 있다. 





또한, 컨테이너를 실행할 때는 분리된 프로세스로 실행되기 때문에 문제 없이 잘 실행된다. 





참고 

* docker의 내부구조에 대한 설명 :
https://docs.docker.com/engine/userguide/storagedriver/imagesandcontainers/





Posted by '김용환'
,



http://developers.redhat.com/blog/2016/02/24/10-things-to-avoid-in-docker-containers/



레드햇 개발자 블로그에 좋은 내용이 좀 있다.




10 things to avoid in docker containers 라는 블로그을 잠깐 소개한다.


도커의 장점

1. Containers are immutable 

2. Containers are lightweight

3. Containers are fast


피해야 10가지 내용- Don't

1. Don’t store data in containers 
컨테이너는 언제든지 바뀌질 수 있고 사라질 수 있고 멈춰질 수 있다.  데이터 손실에 대한 영향도를 살펴야 한다.

2. Don’t ship your application in two pieces 
애플리케이션을 2로 나누지 말라. 개발 단계(디버그)에서는 상관없지만, 상용 배포에서는 하나로 만든다.

3. Don’t create large images 
큰 이미지는 배포하기 어렵다. 불필요한 패키지는 설치하지 않는다.

4. Don’t use a single layer image
관리를 편하게 하라

5. Don’t create images from running containers 
이미지를 생성하는 docker commit 커맨드를 사용하지 않는다.

6. Don’t use only the “latest” tag 
latest는 maven의 snapshot을 의미한다. 하위 호환성을 조심해야 한다.

7. Don’t run more than one process in a single container 
하나의 컨테이너에 하나 이상의 프로세스를 실행하지 않는다.

8. Don’t store credentials in the image. Use environment variables 
이미지에 중요 크레덴셜(username/password)를 저장하지 않는다.

9. Don’t run processes as a root user 
보안 문제가 언제든지 발생할 수 있다.

10. Don’t rely on IP addresses 
IP는 언제든지 변할 수 있다.





Posted by '김용환'
,


docker 1.12를 사용 중이다.

Docker version 1.12.0-rc4, build e4a0dbc, experimental



mac의 디렉토리를 docker의 리눅스 디렉토리로 복사할 때, 에러가 발생할 수 있다.


docker: Error response from daemon: Mounts denied:

are not shared from OS X and do not belong to the system.

You can configure shared paths from Docker -> Preferences...



이런 에러를 처리하는 방법을 소개한다.



맥에서 docker container로 복사할 때, 정해진 디렉토리만 복사할 수 있다.

/Users, /Volumes, /private, /tmp 이다. 





만약, 기본 디렉토리 외에 다른 디렉토리를 docker container로 복사하려고 할 때가 문제가 될 수 있다.



예) 실행 커맨드

docker run \
-v /mydev/google-sandbox/volume/data:/data \
-v /mydev/google-sandbox/volume/log:/log \
..


에러가 아래처럼 발생했다.



docker: Error response from daemon: Mounts denied:

RROR

The paths /mydev/google-sandbox/data and /mydev/google-spec/docker/google-sandbox/0/log

are not shared from OS X and do not belong to the system.

You can configure shared paths from Docker -> Preferences...

..



Docker 설정에 File sharing 디렉토리를 추가하면, 에러는 발생하지 않는다. 






Posted by '김용환'
,

환경 : docker 1.12, host mac 


맥에서 docker container를 테스트할 수 있는 환경과 linux에서 동작하는 docker를 개발하고 있다.




docke의 /data/start.sh는 주로 데몬으로 사용하는데, 만약 이미지를 만드는 도중에 디버깅을 해야 하거나, push하기 전에 container로 띄워서 불필요한 내용을 정리해야 할 상황이 생길 수 있다. 그 때를 위한 예제이다.




먼저 centos를 기반으로 하고, 여러 애플리케이션이 들어가 있는 도커 이미지를 만들었다. 


$ docker build -t google-sandbox -f Dockerfile .



/data/start.sh 파일이 docker에 존재하지 않으면, docker run 커맨드로 실행을 시킬려면 에러가 발생한다.



$ docker run -i -t --name test google-sandbox /bin/bash

sh: /data/start.sh: No such file or directory




Dockerfile에 이렇게 추가해도. 실행이 되지 않는다. 즉 dummy script는 안된다.


RUN mkdir -p /data && touch /data/start.sh



그래서 docker 이미지에 /data/start.sh에 먼가 길게 동작하는 스크립트로 만든다.


RUN mkdir -p /data && echo $'#/bin/bash\n\
while true; do echo hello world; sleep 10000; done\n\
'\
> /data/start.sh


그리고, docker를 실행한다. 



(가장 중요한 부분은 -d 이다!!)

$  docker run --name test -d google-sandbox /bin/bash -c "echo 1"

ae5f0d3ec968f55c0893d68a23d9033f62471555aa0b65785af946cf86eeec44


$ docker ps

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES

ae5f0d3ec968        google-sandbox       "/docker-entrypoint.s"   3 seconds ago       Up 2 seconds                            test



$ docker exec -i -t test /bin/bash

(docker 서버로 진입)

[root@ae5f0d3ec968 /]# ls -al

total 96

....


쉘을 종료했다가 나갔다가도 다시 들어올 수 있다.

$  docker exec -i -t google-sandbox1 /bin/bash
[root@ ae5f0d3ec968 /]#


로그를 보면 /data/start.sh가 실행하고 있음을 확인할 수 있다.


$ docker logs 컨테이너ID

hello world




참고로, 데몬(-d)를 주지 않으면 /data/start.sh의 실행 모드 이동되니. 쓰지 않도록 한다.


$ docker run -i -t --name google-sandbox google-sandbox /bin/bash

hello world

(대기)






참고 자료

https://docs.docker.com/engine/tutorials/dockerizing/

https://docs.docker.com/engine/reference/run/

https://docs.docker.com/v1.10/engine/quickstart/





참고로 테스트하면서 자주 만드는 명령어 추가.


* 사용하지 않는 docker 컨테이너 삭제하기


docker rm `docker ps -a -q`


Posted by '김용환'
,




$ mkdir centos7-expressjs

$ cd centos7-expressjs

$ vi Dockerfile

FROM centos:centos7

RUN yum install -y epel-release;yum install -y npm;

RUN npm install express --save

COPY . ./src

EXPOSE 8080

CMD ["node", "/src/index.js"]


$ vi index.js

var express = require('express'), app = express();

app.get('/', function (req, res) {res.send('Hello World!\n');});

app.listen(8080);


$ docker build -t knight76/centos7-expressjs .

$ docker run -p 8081:8080 -d  knight76/centos7-expressjs

$ curl -i localhost:8081

 

HTTP/1.1 200 OK

X-Powered-By: Express

Content-Type: text/html; charset=utf-8

Content-Length: 13

ETag: W/"d-jd2L5LF5pSmvpfL/rkuYWA"

Date: Tue, 26 Jul 2016 09:43:28 GMT

Connection: keep-alive


Hello World! 



----------------------


도커 허브에 업로드 한다.


우선 https://hub.docker.com에 이메일 계정으로 가입한다.



$ docker login

Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one.

Username: 

Password:

Login Succeeded

  


$ docker push knight76/centos7-expressjs

(한국이라 그런지, push 시간이 오래 걸린다.)




$ docker search expressjs

NAME                                      DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED

dmportella/expressjs                      Simple expressjs site with a status route ...   0

....

knight76/expressjs ...

Posted by '김용환'
,

docker를 이용해서 wordpress 테스트 환경을 구축할 수 있다.

wordpress 도커는 mysql을 함께 실행하지 않기 때문에 mysql은 도커 컨테이너를 따로 실행한다.




mysql 5.7 도커 컨테이너를 실행하고 제대로 동작하는지 docker ps로 확인한다.


$ docker run --restart=always --name wordpressdb -e MYSQL_ROOT_PASSWORD=123 -e MYSQL_DATABASE=wordpress -d mysql:5.7


$ docker ps

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES

a54634841ccd        mysql:5.7           "docker-entrypoint.sh"   2 minutes ago       Up 2 minutes        3306/tcp            wordpressdb




wordpress 도커 컨테이너를 실행한다. -p 매개변수는 8080 으로 요청하면 컨테이너에서는 80으로 forwarding 한다.


$ docker run --restart=always -e WORDPRESS_DB_PASSWORD=123 -d --name wordpress --link wordpressdb:mysql -p 8080:80 wordpress




이제 2 개의 도커 컨테이너가 실행 중이다.


$ docker ps

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES

76d768dbe13c        wordpress           "/entrypoint.sh apach"   17 minutes ago      Up 17 minutes       0.0.0.0:8080->80/tcp   wordpress

a54634841ccd        mysql:5.7           "docker-entrypoint.sh"   23 minutes ago      Up 23 minutes       3306/tcp               wordpressdb




wordpress 도커 컨테이너 설정을 모두 얻는다. 대략적인 정보를 확인할 수 있다.


$ docker inspect wordpress

[

    {

        "Id": "76d768dbe13cd17c0701c12943170e33de12f9f9853191352f34e7fb5f0b7111",

        "Created": "2016-07-24T13:41:50.569702368Z",

        "Path": "/entrypoint.sh",

        "Args": [

            "apache2-foreground"

        ],

        "State": {

            "Status": "running",

            "Running": true,

            "Paused": false,

            "Restarting": false,

            "OOMKilled": false,

            "Dead": false,

            "Pid": 2655,

            "ExitCode": 0,

            "Error": "",

            "StartedAt": "2016-07-24T13:41:51.086400125Z",

            "FinishedAt": "0001-01-01T00:00:00Z"

        },

        "Image": "sha256:ba0d4f420656196a96f3106b8e22b4e2c00351e48b5218456a8e4833051cc816",

        "ResolvConfPath": "/var/lib/docker/containers/76d768dbe13cd17c0701c12943170e33de12f9f9853191352f34e7fb5f0b7111/resolv.conf",

        "HostnamePath": "/var/lib/docker/containers/76d768dbe13cd17c0701c12943170e33de12f9f9853191352f34e7fb5f0b7111/hostname",

        "HostsPath": "/var/lib/docker/containers/76d768dbe13cd17c0701c12943170e33de12f9f9853191352f34e7fb5f0b7111/hosts",

        "LogPath": "/var/lib/docker/containers/76d768dbe13cd17c0701c12943170e33de12f9f9853191352f34e7fb5f0b7111/76d768dbe13cd17c0701c12943170e33de12f9f9853191352f34e7fb5f0b7111-json.log",

        "Name": "/wordpress",

        "RestartCount": 0,

        "Driver": "aufs",

        "MountLabel": "",

        "ProcessLabel": "",

        "AppArmorProfile": "",

        "ExecIDs": null,

        "HostConfig": {

            "Binds": null,

            "ContainerIDFile": "",

            "LogConfig": {

                "Type": "json-file",

                "Config": {}

            },

            "NetworkMode": "default",

            "PortBindings": {

                "80/tcp": [

                    {

                        "HostIp": "",

                        "HostPort": "8080"

                    }

                ]

            },

            "RestartPolicy": {

                "Name": "always",

                "MaximumRetryCount": 0

            },

            "AutoRemove": false,

            "VolumeDriver": "",

            "VolumesFrom": null,

            "CapAdd": null,

            "CapDrop": null,

            "Dns": [],

            "DnsOptions": [],

            "DnsSearch": [],

            "ExtraHosts": null,

            "GroupAdd": null,

            "IpcMode": "",

            "Cgroup": "",

            "Links": [

                "/wordpressdb:/wordpress/mysql"

            ],

            "OomScoreAdj": 0,

            "PidMode": "",

            "Privileged": false,

            "PublishAllPorts": false,

            "ReadonlyRootfs": false,

            "SecurityOpt": null,

            "UTSMode": "",

            "UsernsMode": "",

            "ShmSize": 67108864,

            "Runtime": "runc",

            "ConsoleSize": [

                0,

                0

            ],

            "Isolation": "",

            "CpuShares": 0,

            "Memory": 0,

            "CgroupParent": "",

            "BlkioWeight": 0,

            "BlkioWeightDevice": null,

            "BlkioDeviceReadBps": null,

            "BlkioDeviceWriteBps": null,

            "BlkioDeviceReadIOps": null,

            "BlkioDeviceWriteIOps": null,

            "CpuPeriod": 0,

            "CpuQuota": 0,

            "CpusetCpus": "",

            "CpusetMems": "",

            "Devices": [],

            "DiskQuota": 0,

            "KernelMemory": 0,

            "MemoryReservation": 0,

            "MemorySwap": 0,

            "MemorySwappiness": -1,

            "OomKillDisable": false,

            "PidsLimit": 0,

            "Ulimits": null,

            "CpuCount": 0,

            "CpuPercent": 0,

            "IOMaximumIOps": 0,

            "IOMaximumBandwidth": 0

        },

        "GraphDriver": {

            "Name": "aufs",

            "Data": null

        },

        "Mounts": [

            {

                "Name": "e0b6d751c7432e4be06a0c0173a70071f0730a42acc3a751a22d45f489011c13",

                "Source": "/var/lib/docker/volumes/e0b6d751c7432e4be06a0c0173a70071f0730a42acc3a751a22d45f489011c13/_data",

                "Destination": "/var/www/html",

                "Driver": "local",

                "Mode": "",

                "RW": true,

                "Propagation": ""

            }

        ],

        "Config": {

            "Hostname": "76d768dbe13c",

            "Domainname": "",

            "User": "",

            "AttachStdin": false,

            "AttachStdout": false,

            "AttachStderr": false,

            "ExposedPorts": {

                "80/tcp": {}

            },

            "Tty": false,

            "OpenStdin": false,

            "StdinOnce": false,

            "Env": [

                "WORDPRESS_DB_PASSWORD=123",

                "no_proxy=*.local, 169.254/16",

                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",

                "PHPIZE_DEPS=autoconf \t\tfile \t\tg++ \t\tgcc \t\tlibc-dev \t\tmake \t\tpkg-config \t\tre2c",

                "PHP_INI_DIR=/usr/local/etc/php",

                "APACHE_CONFDIR=/etc/apache2",

                "APACHE_ENVVARS=/etc/apache2/envvars",

                "PHP_EXTRA_BUILD_DEPS=apache2-dev",

                "PHP_EXTRA_CONFIGURE_ARGS=--with-apxs2",

                "GPG_KEYS=0BD78B5F97500D450838F95DFE857D9A90D90EC1 6E4F6AB321FDC07F2C332E3AC2BF0BC433CFC8B3",

                "PHP_VERSION=5.6.23",

                "PHP_FILENAME=php-5.6.23.tar.xz",

                "PHP_SHA256=39141e9a617af172aedbbacee7a63eb15502850f7cea20d759a9cffa7cfb0a1a",

                "WORDPRESS_VERSION=4.5.3",

                "WORDPRESS_SHA1=835b68748dae5a9d31c059313cd0150f03a49269"

            ],

            "Cmd": [

                "apache2-foreground"

            ],

            "Image": "wordpress",

            "Volumes": {

                "/var/www/html": {}

            },

            "WorkingDir": "/var/www/html",

            "Entrypoint": [

                "/entrypoint.sh"

            ],

            "OnBuild": null,

            "Labels": {}

        },

        "NetworkSettings": {

            "Bridge": "",

            "SandboxID": "ef789188d36c51bce68235e3dc7385a7f0b6c1f64579f225927f5b8e5a690a51",

            "HairpinMode": false,

            "LinkLocalIPv6Address": "",

            "LinkLocalIPv6PrefixLen": 0,

            "Ports": {

                "80/tcp": [

                    {

                        "HostIp": "0.0.0.0",

                        "HostPort": "8080"

                    }

                ]

            },

            "SandboxKey": "/var/run/docker/netns/ef789188d36c",

            "SecondaryIPAddresses": null,

            "SecondaryIPv6Addresses": null,

            "EndpointID": "c24808d9ef0f20266cd0c16337de7b2d88939853afdc5893a2d1898741f0e292",

            "Gateway": "172.17.0.1",

            "GlobalIPv6Address": "",

            "GlobalIPv6PrefixLen": 0,

            "IPAddress": "172.17.0.3",

            "IPPrefixLen": 16,

            "IPv6Gateway": "",

            "MacAddress": "02:42:ac:11:00:03",

            "Networks": {

                "bridge": {

                    "IPAMConfig": null,

                    "Links": null,

                    "Aliases": null,

                    "NetworkID": "1a45bc6e96c0909fea2d34bc6b1492adc2839f9d5f893ca013af9300aad4fc33",

                    "EndpointID": "c24808d9ef0f20266cd0c16337de7b2d88939853afdc5893a2d1898741f0e292",

                    "Gateway": "172.17.0.1",

                    "IPAddress": "172.17.0.3",

                    "IPPrefixLen": 16,

                    "IPv6Gateway": "",

                    "GlobalIPv6Address": "",

                    "GlobalIPv6PrefixLen": 0,

                    "MacAddress": "02:42:ac:11:00:03"

                }

            }

        }

    }

]




컨테이너 로그를 확인한다.


$ docker logs -f wordpress

WordPress not found in /var/www/html - copying now...

Complete! WordPress has been successfully copied to /var/www/html

AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.17.0.3. Set the 'ServerName' directive globally to suppress this message

AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.17.0.3. Set the 'ServerName' directive globally to suppress this message

[Sun Jul 24 13:41:52.317876 2016] [mpm_prefork:notice] [pid 1] AH00163: Apache/2.4.10 (Debian) PHP/5.6.23 configured -- resuming normal operations

[Sun Jul 24 13:41:52.317926 2016] [core:notice] [pid 1] AH00094: Command line: 'apache2 -D FOREGROUND'





웹 브라우져에서 다음을 실행하면 wordpress 설치화면이 나타난다.



http://localhost:8080 또는


http://localhost:8080/wp-admin/install.php






그리고 $ docker logs -f wordpress 결과에 아파치 로그가 출력된다.


172.17.0.1 - - [24/Jul/2016:14:01:44 +0000] "GET / HTTP/1.1" 302 397 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"

172.17.0.1 - - [24/Jul/2016:14:01:44 +0000] "GET /wp-admin/install.php HTTP/1.1" 200 3433 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"

....



참고로 docker ps는 현재 실행 중인 도커 컨테이너를 출력하고, docker ps -a는 모든 도커 컨테이너를 출력한다. 상태 정보로 확인할 수 있다.


~$ docker ps

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES

76d768dbe13c        wordpress           "/entrypoint.sh apach"   21 minutes ago      Up 21 minutes       0.0.0.0:8080->80/tcp   wordpress

a54634841ccd        mysql:5.7           "docker-entrypoint.sh"   27 minutes ago      Up 27 minutes       3306/tcp               wordpressdb



~$ docker ps -a

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS                    NAMES

76d768dbe13c        wordpress           "/entrypoint.sh apach"   21 minutes ago      Up 21 minutes               0.0.0.0:8080->80/tcp     wordpress

a54634841ccd        mysql:5.7           "docker-entrypoint.sh"   27 minutes ago      Up 27 minutes               3306/tcp                 wordpressdb

5f615fc3de99        hello-world         "bash"                   32 minutes ago      Created                                              furious_wozniak

.....






실행 중인 wordpress와 mysql 도커 컨네이너를 모두 stop 시킨다.


$ docker stop 76d768dbe13c

76d768dbe13c

$ docker stop a54634841ccd

a54634841ccd




실행 중인 애플리케이션 목록은 모두 사라진다.


$ docker ps

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES




도커 컨테이너를 실행할 수 있도록 start를 실행한다.


$ docker start a54634841ccd

a54634841ccd

$ docker start 76d768dbe13c

76d768dbe13c




wordpress 도커 컨테이너에 bash 접근을 하려면 docker exec -it 컨테이너ID /bin/bash 또는 docker exec -it 컨테이너ID bash를 실행한다.


$ docker exec -it 76d768dbe13c /bin/bash

root@76d768dbe13c:/var/www/html# hostname

76d768dbe13c

root@76d768dbe13c:/var/www/html# ps -ef | grep apache

root         1     0 24 14:06 ?        00:00:26 apache2 -DFOREGROUND

www-data    54     1  0 14:06 ?        00:00:00 apache2 -DFOREGROUND

www-data    55     1  0 14:06 ?        00:00:00 apache2 -DFOREGROUND

www-data    56     1  0 14:06 ?        00:00:00 apache2 -DFOREGROUND

www-data    57     1  0 14:06 ?        00:00:00 apache2 -DFOREGROUND

www-data    58     1  0 14:06 ?        00:00:00 apache2 -DFOREGROUND

www-data    60     1  0 14:07 ?        00:00:00 apache2 -DFOREGROUND

root        68    61  0 14:08 ?        00:00:00 grep apache

root@76d768dbe13c:/var/www/html# exit

~$




mysql 도커 컨테이너에서도 bash 접근을 할 수 있다.


~$ docker exec -it  a54634841ccd /bin/bash

root@a54634841ccd:/# ps -ef | grep mysql

mysql        1     0  0 14:06 ?        00:00:00 mysqld

root        56    50  0 14:17 ?        00:00:00 grep mysql

root@a54634841ccd:/# ls -al



Posted by '김용환'
,

docker 공부

docker 2016. 7. 24. 05:50


* docker는 Go 로 만들어져 있다 .



* 컨테이너 명령어는 아래 github에 있다.


https://github.com/docker/docker/tree/master/api/client/container


run 커맨드는 create 커맨드와 run 커맨드를 하나로 합쳐 준 기능이다.





* 도커 이미지/컨테이너

도커 이미지는 파일, 

도커 컨테이너는 프로세스




* docker 프로세스 목록 보기

$ docker ps -a

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                     PORTS                    NAMES

66825389a870        hello-world         "/hello"                 40 hours ago        Exited (0) 40 hours ago                             hungry_chandrasekhar

9fb0fc1311ee        054c4599963c        "/bin/sh -c 'mkdir -p"   5 days ago          Exited (0) 5 days ago                               gigantic_jang

f7dd0d66158a        380da3b4d062        "/bin/sh -c 'yum grou"   5 days ago          Exited (0) 5 days ago                               infallible_bose

5ccaea4b7cb9        kite-dns            "sh /app/start"          22 months ago       Exited (0) 11 months ago   172.17.42.1:53->53/udp   kite-dns

e194ffa881eb        dockerfile/ghost    "/bin/bash"              23 months ago       Exited (0) 23 months ago                            prickly_archimedes

123a8a34e793        dockerfile/ghost    "bash /ghost-start"      23 months ago       Exited (0) 22 months ago   0.0.0.0:2368->2368/tcp   cranky_pasteur

e7dff68d8231        dockerfile/ghost    "bash /ghost-start"      23 months ago       Exited (0) 23 months ago                            hungry_sinoussi

41088b37ad02        dockerfile/ghost    "bash /ghost-start"      23 months ago       Exited (0) 23 months ago                            stoic_almeida

36f61ab4f3ae        dockerfile/ghost    "bash /ghost-start"      23 months ago       Exited (0) 23 months ago                            angry_curie


exited 와 up으로 대충 구분할 수 있다. exited는 종료된 것, up은 실행 중임을 의미한다.


docker ps 는 실행 중인 도커 프로세스의 목록을 출력한다.


$ docker ps

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES

76d768dbe13c        wordpress           "/entrypoint.sh apach"   About an hour ago   Up About an hour    0.0.0.0:8080->80/tcp   wordpress

a54634841ccd        mysql:5.7           "docker-entrypoint.sh"   About an hour ago   Up About an hour    3306/tcp               wordpressdb




* 도커 컨테이너를 시작하려면 docker start를 실행한다.

$ docker start wordexpress


* 도커 컨테이너를 종료하려면 docker stop를 실행한다.

$ docker stop wordexpress



* 도커 컨테이너를 삭제하려면 docker rm을 실행한다.


$ docker ps -a  | grep hello

5f615fc3de99        hello-world         "bash"                   About an hour ago   Created                                                 furious_wozniak

686db8babcdb        hello-world         "/hello"                 About an hour ago   Exited (0) About an hour ago                            evil_bohr

66825389a870        hello-world         "/hello"                 2 days ago          Exited (0) 2 days ago                                   hungry_chandrasekhar

~$ docker rm 5f615fc3de99  686db8babcdb  66825389a870

5f615fc3de99

686db8babcdb

66825389a870

~$ docker ps -a  | grep hello

// 없음





* 도커 컨테이너에 접근하려면 docker exec container_id /bin/bash를 실행한다.




* 도커 컨네이버 검색하려면 docker search 커맨드를 사용한다.

$docker search express

$docker search node

$docker search centos



* 도커 허브 로그인

$ docker login

Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one.

Username:



* docker 명령어 잘 보기

docker 커맨드에 --help 잘 살펴보기



$ docker  --help

Usage: docker [OPTIONS] COMMAND [arg...]

       docker [ --help | -v | --version ]


A self-sufficient runtime for containers.


Options:


  --config=~/.docker              Location of client config files

  -D, --debug                     Enable debug mode

  -H, --host=[]                   Daemon socket(s) to connect to

  -h, --help                      Print usage

  -l, --log-level=info            Set the logging level

  --tls                           Use TLS; implied by --tlsverify

  --tlscacert=~/.docker/ca.pem    Trust certs signed only by this CA

  --tlscert=~/.docker/cert.pem    Path to TLS certificate file

  --tlskey=~/.docker/key.pem      Path to TLS key file

  --tlsverify                     Use TLS and verify the remote

  -v, --version                   Print version information and quit


Commands:

    attach    Attach 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

    deploy    Create and update a stack from a Distributed Application Bundle (DAB)

    diff      Inspect changes 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 a container, image or task

    kill      Kill one or more running container

    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

    network   Manage Docker networks

    node      Manage Docker Swarm nodes

    pause     Pause all processes within one or more containers

    plugin    Manage Docker plugins

    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 a container

    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 Hu



$ docker login --help


Usage: docker login [OPTIONS] [SERVER]


Log in to a Docker registry.

If no server is specified, the default is defined by the daemon.


Options:

      --help              Print usage

  -p, --password string   Password

  -u, --username string   Username




$ docker run --help


Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]


Run a command in a new container


Options:

      --add-host value              Add a custom host-to-IP mapping (host:ip) (default [])

  -a, --attach value                Attach to STDIN, STDOUT or STDERR (default [])

      --blkio-weight value          Block IO (relative weight), between 10 and 1000

      --blkio-weight-device value   Block IO weight (relative device weight) (default [])

      --cap-add value               Add Linux capabilities (default [])

      --cap-drop value              Drop Linux capabilities (default [])

      --cgroup-parent string        Optional parent cgroup for the container

      --cidfile string              Write the container ID to the file

      --cpu-percent int             CPU percent (Windows only)

      --cpu-period int              Limit CPU CFS (Completely Fair Scheduler) period

      --cpu-quota int               Limit CPU CFS (Completely Fair Scheduler) quota

  -c, --cpu-shares int              CPU shares (relative weight)

      --cpuset-cpus string          CPUs in which to allow execution (0-3, 0,1)

      --cpuset-mems string          MEMs in which to allow execution (0-3, 0,1)

  -d, --detach                      Run container in background and print container ID

      --detach-keys string          Override the key sequence for detaching a container

      --device value                Add a host device to the container (default [])

      --device-read-bps value       Limit read rate (bytes per second) from a device (default [])

      --device-read-iops value      Limit read rate (IO per second) from a device (default [])

      --device-write-bps value      Limit write rate (bytes per second) to a device (default [])

      --device-write-iops value     Limit write rate (IO per second) to a device (default [])

      --disable-content-trust       Skip image verification (default true)

      --dns value                   Set custom DNS servers (default [])

      --dns-opt value               Set DNS options (default [])

      --dns-search value            Set custom DNS search domains (default [])

      --entrypoint string           Overwrite the default ENTRYPOINT of the image

  -e, --env value                   Set environment variables (default [])

      --env-file value              Read in a file of environment variables (default [])

      --expose value                Expose a port or a range of ports (default [])

      --group-add value             Add additional groups to join (default [])

      --health-cmd string           Command to run to check health

      --health-interval duration    Time between running the check

      --health-retries int          Consecutive failures needed to report unhealthy

      --health-timeout duration     Maximum time to allow one check to run

      --help                        Print usage

  -h, --hostname string             Container host name

  -i, --interactive                 Keep STDIN open even if not attached

      --io-maxbandwidth string      Maximum IO bandwidth limit for the system drive (Windows only)

      --io-maxiops uint             Maximum IOps limit for the system drive (Windows only)

      --ip string                   Container IPv4 address (e.g. 172.30.100.104)

      --ip6 string                  Container IPv6 address (e.g. 2001:db8::33)

      --ipc string                  IPC namespace to use

      --isolation string            Container isolation technology

      --kernel-memory string        Kernel memory limit

  -l, --label value                 Set meta data on a container (default [])

      --label-file value            Read in a line delimited file of labels (default [])

      --link value                  Add link to another container (default [])

      --link-local-ip value         Container IPv4/IPv6 link-local addresses (default [])

      --log-driver string           Logging driver for container

      --log-opt value               Log driver options (default [])

      --mac-address string          Container MAC address (e.g. 92:d0:c6:0a:29:33)

  -m, --memory string               Memory limit

      --memory-reservation string   Memory soft limit

      --memory-swap string          Swap limit equal to memory plus swap: '-1' to enable unlimited swap

      --memory-swappiness int       Tune container memory swappiness (0 to 100) (default -1)

      --name string                 Assign a name to the container

      --network string              Connect a container to a network (default "default")

      --network-alias value         Add network-scoped alias for the container (default [])

      --no-healthcheck              Disable any container-specified HEALTHCHECK

      --oom-kill-disable            Disable OOM Killer

      --oom-score-adj int           Tune host's OOM preferences (-1000 to 1000)

      --pid string                  PID namespace to use

      --pids-limit int              Tune container pids limit (set -1 for unlimited)

      --privileged                  Give extended privileges to this container

  -p, --publish value               Publish a container's port(s) to the host (default [])

  -P, --publish-all                 Publish all exposed ports to random ports

      --read-only                   Mount the container's root filesystem as read only

      --restart string              Restart policy to apply when a container exits (default "no")

      --rm                          Automatically remove the container when it exits

      --runtime string              Runtime to use for this container

      --security-opt value          Security Options (default [])

      --shm-size string             Size of /dev/shm, default value is 64MB

      --sig-proxy                   Proxy received signals to the process (default true)

      --stop-signal string          Signal to stop a container, SIGTERM by default (default "SIGTERM")

      --storage-opt value           Set storage driver options per container (default [])

      --sysctl value                Sysctl options (default map[])

      --tmpfs value                 Mount a tmpfs directory (default [])

  -t, --tty                         Allocate a pseudo-TTY

      --ulimit value                Ulimit options (default [])

  -u, --user string                 Username or UID (format: <name|uid>[:<group|gid>])

      --userns string               User namespace to use

      --uts string                  UTS namespace to use

  -v, --volume value                Bind mount a volume (default [])

      --volume-driver string        Optional volume driver for the container

      --volumes-from value          Mount volumes from the specified container(s) (default [])

  -w, --workdir string              Working directory inside the container




* 이미지를 도커 허브에 올릴 수 있다.

참고,  $ man Dockerfile


Posted by '김용환'
,

[docker] docker 설치

docker 2016. 7. 22. 18:22


docker는 linux 와 맥을 포함한 다양한 운영 체제에서 동작할 수 있다. 

https://docs.docker.com/engine/installation/


맥에서는 쉽게 설치할 수 있다.

https://docs.docker.com/engine/installation/mac/

https://docs.docker.com/docker-for-mac/


순서대로 진행한다.


~$ docker --version

Docker version 1.12.0-rc4, build e4a0dbc, experimental


제대로 동작되는지 확인하기 위해 다음을 실행한다.


~$ docker run hello-world

Unable to find image 'hello-world:latest' locally

latest: Pulling from library/hello-world

c04b14da8d14: Pull complete

Digest: sha256:0256e8a36e2070f7bf2d0b0763dbabdd67798512411de4cdcf9431a1feb60fd9

Status: Downloaded newer image for hello-world:latest


Hello from Docker!


This message shows that your installation appears to be working correctly.


To generate this message, Docker took the following steps:

 1. The Docker client contacted the Docker daemon.

 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.

 3. The Docker daemon created a new container from that image which runs the

    executable that produces the output you are currently reading.

 4. The Docker daemon streamed that output to the Docker client, which sent it

    to your terminal.


To try something more ambitious, you can run an Ubuntu container with:

 $ docker run -it ubuntu bash


Share images, automate workflows, and more with a free Docker Hub account:

 https://hub.docker.com


For more examples and ideas, visit:

 https://docs.docker.com/engine/userguide/



용량을 확인하려면 docker images 명령을 실행한다. 


~$ docker images | grep hello

hello-world         latest              c54a2cc56cbb        2 weeks ago         1.848 kB



Centos 7.1에서는 다음과 같이 작업한다.



$ sudo yum update

$ curl -sSL https://get.docker.com/  | sh

$ sudo usermod -aG docker 계정명

$  sudo systemctl start docker

(데몬 실행이 필요하다)


데몬을 실행하지 않으면 docker daemon을 못 찾는 다는 에러가 발생한다.


$ docker run hello-world

docker: Cannot connect to the Docker daemon. Is the docker daemon running on this host?.

See 'docker run --help'.

$ docker ps

Cannot connect to the Docker daemon. Is the docker daemon running on this host?



이럴 때는 sudo systemctl start docker를 제대로 실행 안된 경우일수도 있고 chmod 권한 문제일 수도 있다.


안되면, sudo를 써본다.


$ sudo docker run hello-world

이전 결과와 동일



실행되는 것을 확인할 수 있다.



그리고, docker 데몬이 부팅 후에 자동으로 실행될 수 있도록 다음을 실행하는 것이 좋다.


$ sudo systemctl enable docker





만약 Hello from Docker! 메시지가 발생하지 않으면, 아래 커맨드를 이용해서 443 포트로 ssh 연결이 되는지를 확인해야 한다. proxy 이슈나 컴파일 이슈일 수 있다.


$ openssl s_client -connect index.docker.io:443





참고로 맥에서 vagrant 를 사용하여 centos 7를 설치할 수 있고, 해당 centos 7에서 docker를 설치할 수 있고, docker를 테스트해볼 수 있다.




* 맥 OS x에서 아래와 같은 에러가 발생한다면 제대로 실행이 안된 것이다. 


[~/temp] docker images

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?



docker앱을 설치한 후 docker를 실행한다. 그래서 데몬으로 떠 있어야 한다. 아래와 비슷하게 나오면 성공이다.



$ docker images

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

sandbox       latest              b1c4b0a4a954        9 months ago        3.76 GB

centos              6.7                 fb5054b394b7        10 months ago       191 MB




Posted by '김용환'
,


도커 이미지를 삭제하는 방법은 두 가지이다. 컨테이너 삭제와 이미지 삭제이다.

참조 : https://docs.docker.com/engine/reference/commandline/rm/


* docker rmi : 이미지 삭제

* docker rm : 이미지를 포함한 이미지를 삭제



-f을 주면 강제 삭제한다.




정지된 모든 컨테이너를 삭제하려면, 다음을 실행한다.


$ docker rm $(docker ps -a -q)





도커의 특정 이미지를 삭제하려 할 때, 멈춰진 컨테이너 때문에 삭제가 안될 때가 있다. 이때 컨테이너를 삭제할 때 도움을 받을 수 있다.


$docker rmi 1ce28876c3cc

Error response from daemon: conflict: unable to delete 1ce28876c3cc (must be forced) - image is being used by stopped container 5ccaea4b7cb9



$ docker rm 5ccaea4b7cb9

e98d8053298b



$docker rmi 1ce28876c3cc

Untagged: hello-world:latest

Deleted: sha256:b77358fac48bc0d0b5e547b7b999c5e70a5fde9de9c086b47775568c8b88326d

Deleted: sha256:32ada9ef4cd3ccd536337fbcd8cdb6e026237f59db80498f83f3175176561ffb

Deleted: sha256:3d3313518f8e8d9723adfb09ea58b7a6d46e565979fda05a2073ecb30ca1e3a1

Deleted: sha256:b652ec3a27e758f30de4742156b5d096bb19c82f2dc836e96e430323ba166ffe





목록을 보면 삭제되었다. 


$ docker images

delete됨.





모두 삭제하기


$ docker system prune -a 



Posted by '김용환'
,