隨着微服務的流行,Docker越來越流行,正如它的理念”Build, Ship, and Run Any App, Anywhere”一樣,Docker提供的容器隔離技術使得開發人員不用再去理清server里的各種環境配置,輕松把應用運行起來。我們只需把運行環境的配置和應用封裝在Docker的鏡像(image),然后使用Docker運行這個鏡像即可。Docker可以說是給所有開發人員的一個福利包,學習和使用Docker是所有開發人員的標配技能。
安裝Docker
yum install docker
本文使用的系統是centos7,ubuntu使用以下命令
sudo apt-get update
sudo apt-get install docker-engine
如果報了以下錯誤,是因為yum被其它進程使用了
Another app is currently holding the yum lock; waiting for it to exit... The other application is: PackageKit Memory : 12 M RSS (924 MB VSZ) Started: Mon Jan 2 17:22:13 2017 - 1 day(s) 1:06:13 ago State : Sleeping, pid: 16208
查看正在yum使用的進程
ps -ef|grep yum
kill掉它即可
kill -9 16208
安裝完成,查看安裝是否成功
docker info #查看docker的情況 docker --version #查看docker的版本
啟動Docker服務
service docker start
啟動Docker的hello-world
從Docker Hub下載一個hello-world鏡像
docker pull hello-world
運行hello-world鏡像
docker run hello-word
輸出以下信息
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.
至此,我們已成功運行起第一個Docker容器
tomcat運行環境
1、搜索Docker Hub里的tomcat鏡像
docker search tomcat
- 部分搜索結果如下
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
tomcat Apache Tomcat is an open source implementa... 1132 [OK] dordoka/tomcat Ubuntu 14.04, Oracle JDK 8 and Tomcat 8 ba... 29 [OK] cloudesire/tomcat Tomcat server, 6/7/8 12 [OK] davidcaste/alpine-tomcat Apache Tomcat 7/8 using Oracle Java 7/8 wi... 11 [OK] andreptb/tomcat Debian Jessie based image with Apache Tomc... 6 [OK]
可以看到,星數最高的是官方的tomcat,有關官方tomcat的鏡像可以訪問
https://hub.docker.com/r/library/tomcat/
上面 “7.0.73-jre7, 7.0-jre7, 7-jre7, 7.0.73, 7.0, 7”等等 是這個tomcat庫支持的tag(標簽),這里我們選用的是 “7” 這個標簽
2、拉取Docker Hub里的鏡像
docker pull tomcat:7
3、拉取完成后查看本地的鏡像
docker images #所有鏡像 docker image tomcat:7 #查看REPOSITORY為tomcat:7的鏡像
4、運行tomcat鏡像
docker run tomcat:7
可以訪問 http://ip:8080 確認容器的tomcat已啟動成功
- 使用以下命令來查看正在運行的容器
docker ps
- 若端口被占用,可以指定容器和主機的映射端口
docker run -p 8081:8080 tomcat:7
- 啟動后,訪問地址是http://ip:8081
5、運行我們的web應用
假設我們應用是www,目錄位置在/app/deploy/www
docker run --privileged=true -v /app/deploy/www:/usr/local/tomcat/webapps/www -p 8081:8080 tomcat:7
-v /app/deploy/www:/usr/local/tomcat/webapps/www 是把/app/deploy/www的目錄掛載至容器的/usr/local/tomcat/webapps/www。
–privileged=true是授予docker掛載的權限
至此,已成功把web應用部署在Docker容器運行
常用命令
# 查看所有鏡像 docker images # 正在運行容器 docker ps # 查看docker容器 docker ps -a # 啟動tomcat:7鏡像 docker run -p 8080:8080 tomcat:7 # 以后台守護進程的方式啟動 docker run -d tomcat:7 # 停止一個容器 docker stop b840db1d182b # 進入一個容器 docker attach d48b21a7e439 # 進入正在運行容器並以命令行交互 docker exec -it e9410ee182bd /bin/sh # 以交互的方式運行 docker run -i -t -p 8081:8080 tomcat:7 /bin/bash