Docker 簡介與shell操作使用


一.Docker概述

1.Docker簡介

       Docker是一個開源的應用容器引擎;是一個輕量級容器技術;Docker支持將軟件編譯成一個鏡像;然后在鏡像中各種軟件做好配置,將鏡像發布出去,其他使用者可以直接使  用這個鏡像;運行中的這個鏡像稱為容器,容器啟動是非常快速的。

對比傳統虛擬機總結

 

2.Docker術語

  • docker主機(Host):安裝了Docker程序的機器(Docker直接安裝在操作系統之上);
  • docker客戶端(Client):連接docker主機進行操作; docker倉庫(Registry):用來保存各種打包好的軟件鏡像;
  • docker鏡像(Images):軟件打包好的鏡像;放在docker倉庫中;
  • docker容器(Container):鏡像啟動后的實例稱為一個容器;容器是獨立運行的一個或一組應用。

使用Docker的步驟:

1)、安裝Docker

2)、去Docker倉庫找到這個軟件對應的鏡像;

3)、使用Docker運行這個鏡像,這個鏡像就會生成一個Docker容器;

4)、對容器的啟動停止就是對軟件的啟動停止;

二.Docker安裝

1.安裝linux虛擬機

1)、VMWare、VirtualBox(安裝); VirtualBox下載地址: https://www.virtualbox.org/wiki/Downloads

2)、安裝linux系統CentOS7;

3)、雙擊啟動linux虛擬機;使用 root/ 123456登陸

4)、使用客戶端連接linux服務器進行命令操作;

5)、設置虛擬機網絡;橋接網絡=選好網卡==接入網線;

6)、設置好網絡以后使用命令重啟虛擬機的網絡     service network restart         ip addr

2.linux上安裝docker

1、檢查內核版本,必須是3.10及以上 uname ‐r ,如果不是需要 yum update升級軟件包及內核

2、安裝docker  ,輸入y確認安裝

[root@localhost ~]# yum install docker

yum方式安裝的docker不是最新版的,通過下面方式安裝最新版的docker

[root@localhost ~]# curl -sSL https://get.daocloud.io/docker | sh

3、啟動docker 查看docker版本號

[root@localhost ~]# systemctl start docker

4、設置開機啟動docker

[root@localhost ~]# systemctl enable docker

5、停止docker

[root@localhost ~]# systemctl stop docker

6、查看docker幫助

[root@localhost ~]# docker --help

幫助命令如下:

[root@localhost ~]# docker --help

Usage:  docker COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default "/root/.docker")
  -D, --debug              Enable debug mode
      --help               Print usage
  -H, --host list          Daemon socket(s) to connect to (default [])
  -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 "/root/.docker/ca.pem")
      --tlscert string     Path to TLS certificate file (default "/root/.docker/cert.pem")
      --tlskey string      Path to TLS key file (default "/root/.docker/key.pem")
      --tlsverify          Use TLS and verify the remote
  -v, --version            Print version information and quit

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

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
  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 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.
docker --help

三.Docker鏡像操作

操作

命令

說明

檢索

docker search 關鍵字

egdocker search mysql

我們經常去docker hub上檢索鏡像的詳細信息,如鏡像的TAG

拉取

docker pull 鏡像名:tag

:tag是可選的,tag表示標簽,多為軟件的版本,默認是latest(最新的)

列表

docker images

查看所有本地鏡像

刪除

docker rmi image-id

刪除指定的本地鏡像

1.檢索鏡像

[root@localhost ~]# docker search centos

默認會去 https://hub.docker.com/ 搜索,搜過結果如下

[root@localhost ~]# docker search centos
NAME                               DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
centos                             The official build of CentOS.                   4709                [OK]                
ansible/centos7-ansible            Ansible on Centos7                              118                                     [OK]
jdeathe/centos-ssh                 CentOS-6 6.10 x86_64 / CentOS-7 7.5.1804 x86…   99                                      [OK]
consol/centos-xfce-vnc             Centos container with "headless" VNC session…   63                                      [OK]
imagine10255/centos6-lnmp-php56    centos6-lnmp-php56                              45                                      [OK]
tutum/centos                       Simple CentOS docker image with SSH access      43                                      
centos/mysql-57-centos7            MySQL 5.7 SQL database server                   39                                      
gluster/gluster-centos             Official GlusterFS Image [ CentOS-7 +  Glust…   34                                      [OK]
openshift/base-centos7             A Centos7 derived base image for Source-To-I…   33                                      
centos/python-35-centos7           Platform for building and running Python 3.530                                      
centos/postgresql-96-centos7       PostgreSQL is an advanced Object-Relational …   29                                      
kinogmt/centos-ssh                 CentOS with SSH                                 22                                      [OK]
openshift/jenkins-2-centos7        A Centos7 based Jenkins v2.x image for use w…   15                                      
pivotaldata/centos-gpdb-dev        CentOS image for GPDB development. Tag names…   7                                       
openshift/wildfly-101-centos7      A Centos7 based WildFly v10.1 image for use …   5                                       
openshift/jenkins-1-centos7        DEPRECATED: A Centos7 based Jenkins v1.x ima…   4                                       
darksheer/centos                   Base Centos Image -- Updated hourly             3                                       [OK]
pivotaldata/centos-mingw           Using the mingw toolchain to cross-compile t…   2                                       
pivotaldata/centos                 Base centos, freshened up a little with a Do…   2                                       
blacklabelops/centos               CentOS Base Image! Built and Updates Daily!     1                                       [OK]
pivotaldata/centos-gcc-toolchain   CentOS with a toolchain, but unaffiliated wi…   0                                       
pivotaldata/centos7-test           CentosOS 7 image for GPDB testing               0                                       
pivotaldata/centos7-build          CentosOS 7 image for GPDB compilation           0                                       
smartentry/centos                  centos with smartentry                          0                                       [OK]
jameseckersall/sonarr-centos       Sonarr on CentOS 7                              0                                       [OK]
  • NAME:倉庫名稱
  • DESCRIPTION:鏡像描述
  • STARS:用戶評價,反應一個鏡像的受歡迎程度
  • OFFICIAL:是否官方
  • AUTOMATED:自動構建,表示該鏡像由Docker Hub自動構建流程創建的

2.拉取鏡像

拉取鏡像默認是從docker hub拉取,這是docker默認的公用倉庫,不過缺點是國內下載會比較慢。這里設置從ustc拉取鏡像(建議使用)。

在宿主機器編輯文件:vi /etc/docker/daemon.json,在該配置文件中加入(沒有該文件的話,請先建一個):

{
 "registry-mirrors": ["https://docker.mirrors.ustc.edu.cn"]
}

最后,需要重啟docker服務 systemctl restart docker.service                        執行拉取鏡像命令

[root@localhost ~]# docker pull centos
Using default tag: latest
latest: Pulling from library/centos
256b176beaff: Pull complete 
Digest: sha256:6f6d986d425aeabdc3a02cb61c02abb2e78e57357e92417d6d58332856024faf
Status: Downloaded newer image for centos:latest

3.列表鏡像

[root@localhost ~]# docker images
REPOSITORY                TAG                 IMAGE ID            CREATED             SIZE
docker.io/tomcat          latest              41a54fe1f79d        3 days ago          463 MB
docker.io/centos          latest              5182e96772bf        5 weeks ago         200 MB
  • REPOSITORY:鏡像所在的倉庫名稱
  • TAG:鏡像標簽
  • lMAGE ID:鏡像ID
  • CREATED:鏡像的創建日期(不是獲取該鏡像的日期)
  • SIZE:鏡像大小

這些鏡像都是存儲Docker宿主機的/var/lib/docker目錄

4.刪除鏡像

[root@localhost ~]# docker rmi 41a54fe1f79d

四.Docker容器操作

操作

命令

說明

運行

docker run --name container-name -d image-name

eg:docker run –name myredis –d redis

--name:自定義容器名

-d:后台運行

image-name:指定鏡像模板

列表

docker ps(查看正在運行中的容器);

docker ps -a:查看歷史運行過的容器

docker ps  -l:查看最近運行過的容器

停止

docker stop container-name/container-id

停止當前你運行的容器

啟動

docker start container-name/container-id

啟動容器

刪除

docker rm container-id

刪除指定容器

端口映射

-p 6379:6379

eg:docker run -d -p 6379:6379 --name myredis docker.io/redis

-p: 主機端口(映射到)容器內部的端口

容器日志

docker logs container-name/container-id

 

更多命令

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

1.啟動容器

1)以交互方式啟動容器:docker run -it --name 容器名稱 鏡像 /bin/bash;

  • -i:表示以“交互模式”運行容器
  • -t:表示容器啟動后會進入其命令行。加入這兩個參數后,容器創建就能登錄進去。即分配一個偽終端。
  • --name :為創建的容器命名。
  • -v:表示目錄映射關系(前者是宿主機目錄,后者是映射到宿主機上的目錄),可以使用多個-v做多個目錄或文件映射。注意:最好做目錄映射,在宿主機上做修改,然后共享到容器上。
  • -d:在run后面加上-d參數,則會創建一個守護式容器在后台運行(這樣創建容器后不會自動登錄容器,如果只加-i -t兩個參數,創建后就會自動進去容器)。
  • -p:表示端口映射,前者是宿主機端口,后者是容器內的映射端口。可以使用多個-p做多個端口映射

創建一個交互式容器並取名為mycentos

[root@localhost docker]# docker run -i -t --name=mycentos centos /bin/bash

2)以守護進程后台方式啟動容器:docker run -d --name 容器名稱 鏡像

[root@localhost ~]# docker search tomcat                                       #搜索tomcat
[root@localhost ~]# docker pull tomcat                                         #拉取tomcat鏡像
[root@localhost ~]# docker run -d --name mytomcat -p 8888:8080 tomcat:latest   #啟動tomcat容器,並做端口映射
[root@localhost ~]# docker  ps                                                 #查看容器運行列表

2.停止容器

 docker stop 容器名稱或者容器ID

[root@localhost ~]# docker stop 62a021b1c0fd 

3.重啟容器

 docker start 容器名稱或者容器ID

[root@localhost ~]# docker start  62a021b1c0fd 

4.刪除容器

刪除容器必須是已經停止的容器,刪除指定容器:docker rm 容器名稱或者容器ID;刪除所有容器:docker rm ‘docker ps -a -q’

[root@localhost ~]# docker rm 62a021b1c0fd

五.Docker下部署應用程序

1. 構建鏡像方案

  • 方案一:直接通過docker pull拉取別人提交好的tomcatnginx等應用程序鏡像,然后基於這些鏡像去創建容器。
  • 方案:通過dockerfile制作自己的應用程序鏡像
  • 方案:根據系統鏡像創建Docker容器,這個時候Docker就相當於一個虛擬機,然后進入容器部署對應的應用。具體步驟如下:
  1. 啟動Centos系統鏡像的容器my_container;
  2. 在該容器中部署應用程序,例如:Tomcat、Nginx等;
  3. 將部署完的my_container提交為新的鏡像;
  4. 然后根據新的鏡像去創建容器;
  5. 這個鏡像可以打包,導入到其他的Docker服務器上

2. 構建MySQL鏡像

1、 獲取基礎鏡像CentOS

[root@localhost ~]#  docker pull centos

2、 啟動容器並且在容器內部安裝MySQL

docker run -i -t --name mycentos-mysql centos /bin/bash(通過下面的命令運行centos容器。否則安裝后的mysql無法啟動。)

[root@localhost ~]#  docker run -it --privileged  --name=mycentos-mysql   centos  /usr/sbin/init

另起一個窗口進入容器:[root@localhost ~]#   docker exec -it mycentos-mysql  /bin/bash

[root@53ee11bff386 /]#   yum install -y wget net-tools

[root@53ee11bff386 /]#   wget   http://dev.mysql.com/get/mysql-community-release-el7-5.noarch.rpm

[root@53ee11bff386 /]#   rpm -ivh mysql-community-release-el7-5.noarch.rpm

[root@53ee11bff386 /]#   yum install mysql-community-server

3、 啟動mysql,並設置密碼

[root@53ee11bff386 /]#   systemctl start mysqld

[root@53ee11bff386 /]#   mysql -uroot -p  回車

mysql>    SET PASSWORD = PASSWORD('123456');

mysql>    GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '123456' WITH GRANT OPTION;

mysql>    FLUSH PRIVILEGES;

mysql>   exit;

4、 提交為新鏡像

[root@localhost ~]# docker commit mycentos-mysql mysql5.6
[root@localhost ~]# docker images

5、 啟動mysql容器

[root@localhost ~]# docker run -d -e "container=docker" --privileged=true --name mysql5.6 -p 3306:3306 mysql5.6 

6、 進入容器啟動MySQL服務

[root@localhost ~]#  docker exec -it mysql5.6 /bin/bash
[root@6dda80c75bfc /]#  systemctl start mysql

7、 Navicat連接

8、 上傳鏡像到Docker hub

  • 注冊Docker hub賬號,Docker Hub注冊后創建private/publicRepository
  • 登錄docker login   [root@localhost ~]#  docker login
  • tag修改鏡像名稱             [root@localhost ~]#      docker tag mysql5.6 frank409167848/centos7-mysql5.6
  • 推送docker push   [root@localhost ~]#  docker push frank409167848/centos7-mysql5.6
  • Docker hub 查看
  • 下載

六.報錯問題

1.啟動docker報錯

[root@localhost ~]# systemctl start docker
Job for docker.service failed because the control process exited with error code. See "systemctl status docker.service" and "journalctl -xe" for details.

查看docker狀態

[root@localhost ~]# systemctl status docker.service
● docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Sun 2018-09-16 04:13:30 EDT; 8min ago
     Docs: http://docs.docker.com
  Process: 2124 ExecStart=/usr/bin/dockerd-current --add-runtime docker-runc=/usr/libexec/docker/docker-runc-current --default-runtime=dock
er-runc --exec-opt native.cgroupdriver=systemd --userland-proxy-path=/usr/libexec/docker/docker-proxy-current --init-path=/usr/libexec/dock
er/docker-init-current --seccomp-profile=/etc/docker/seccomp.json $OPTIONS $DOCKER_STORAGE_OPTIONS $DOCKER_NETWORK_OPTIONS $ADD_REGISTRY $B
LOCK_REGISTRY $INSECURE_REGISTRY $REGISTRIES (code=exited, status=1/FAILURE)
 Main PID: 2124 (code=exited, status=1/FAILURE)

Sep 16 04:13:27 localhost.localdomain systemd[1]: Starting Docker Application Container Engine...
Sep 16 04:13:29 localhost.localdomain dockerd-current[2124]: time="2018-09-16T04:13:29.348086797-04:00" level=warning msg="could no...ound"
Sep 16 04:13:29 localhost.localdomain dockerd-current[2124]: time="2018-09-16T04:13:29.365854628-04:00" level=info msg="libcontaine...2128"
Sep 16 04:13:30 localhost.localdomain dockerd-current[2124]: time="2018-09-16T04:13:30.457340010-04:00" level=warning msg="overlay2: the...
Sep 16 04:13:30 localhost.localdomain dockerd-current[2124]: Error starting daemon: SELinux is not supported with the overlay2 grap...alse)
Sep 16 04:13:30 localhost.localdomain systemd[1]: docker.service: main process exited, code=exited, status=1/FAILURE
Sep 16 04:13:30 localhost.localdomain systemd[1]: Failed to start Docker Application Container Engine.
Sep 16 04:13:30 localhost.localdomain systemd[1]: Unit docker.service entered failed state.
Sep 16 04:13:30 localhost.localdomain systemd[1]: docker.service failed.
Hint: Some lines were ellipsized, use -l to show in full.

Solutions:根據高亮的錯誤日志得知,此linux的內核中的SELinux不支持 overlay2 graph driver ,解決方法有兩個,要么啟動一個新內核,要么就在docker里禁用selinux,--selinux-enabled=false

重新編輯docker配置文件:# vi /etc/sysconfig/docker

如上改為--selinux-enabled=false后保存,重啟docker,搞定!

2.啟動mysql報錯

[root@dfb1cc594f9b /]# systemctl start mysql
Failed to get D-Bus connection: Operation not permitted

解決辦法

生成容器: # docker run -d -e "container=docker" --privileged=true --name mysql5.6 -p 3306:3306 mysql5.6 

進入容器: # docker exec -it mysql /bin/bash

這樣可以使用systemctl啟動服務了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM