Docker(1): 初步使用

Docker安装

系统环境CentOS7

  1. 安装:yum install docker
  2. Docker镜像加速:
    使用DaoCloud.io提供的镜像加速。
    curl -sSL https://get.daocloud.io/daotools/set_mirror.sh | sh -s http://5dc86619.m.daocloud.io

编译自己的镜像

创建一个Spring Boot项目

Hello, Docker!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
public class DemoApplication {
@RequestMapping("/")
public String index(){
return "Hello, Docker!";
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

将项目打包 mvn package, demo-0.0.1-SNAPSHOT.jar

创建Dockerfile文件

内容如下:

1
2
3
4
5
6
7
8
9
FROM java:8
MAINTAINER roger
ADD demo-0.0.1-SNAPSHOT.jar spring-boot-hello.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/spring-boot-hello.jar"]

  • FROM:指明当前镜像的基镜像是Java,标签(版本)为8
  • MANINTAINER:作者roger
  • ADD:将demo-0.0.1-SNAPSHOT.jar添加到镜像,并重命名为spring-boot-hello.jar
  • EXPOSE:运行镜像的容器,监听8080端口
  • ENTRYPOINT:启动时执行命令java -jar spring-boot-hello.jar

编译镜像

在包括demo-0.0.1-SNAPSHOT.jar和dockerfile文件的目录下执行镜像的编译命令docker build -t roger/spring-boot-hello .roger/spring-boot-hello是镜像的名称,最后一个.指明dockerfile的路径(表明当前路径下)。

编译成功后,查看本地镜像docker images

运行

运行命令:docker run --name spring-boot-hello -p 8080:8080 roger/spring-boot-hello

加上参数-d可以挂起在后台执行。