docker实操记录

137 阅读2分钟

前言

不是系统性的教程,只是个人的实操记录

docker基础概念和命令使用

实操1:使用dockerfile制作程序镜像,并跑起来

编写springboot测试代码,并引入redis。

写一个http接口

@RestController
public class UserController {

    @Autowired
    private RedisTemplate redisTemplate;

    private AtomicLong currentCount = new AtomicLong();

    @GetMapping("view")
    public String viewCount() {
        Long viewCount = redisTemplate.opsForValue().increment("viewCount", 1);
        String currentShow = "<h1>当前访问次数:" + currentCount.incrementAndGet() + "</h1>";
        String totalShow = "<h1>总共访问次数:" + viewCount + "</h1>";
        return currentShow + "<br/>" + totalShow;
    }
}

redis代码

@Configuration
public class RedisConfig {
    @Value ("${spring.redis.host}")
    private String redisHost;
    @Value("${spring.redis.port}")
    private int redisPort;

    @Bean
    public LettuceConnectionFactory lettuceConnectionFactory() {
        RedisStandaloneConfiguration standaloneConfig = new RedisStandaloneConfiguration(redisHost, redisPort);
        return new LettuceConnectionFactory(standaloneConfig);
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(lettuceConnectionFactory());
        template.setKeySerializer(new StringRedisSerializer ());
        template.setValueSerializer(new StringRedisSerializer());
        return template;
    }
}

application.properties配置文件

server.port=80
#这里使用redis-server作为host,作用后面说
spring.redis.host=redis-server
spring.redis.port=6379

使用dockerfile制作程序镜像并跑起来

  1. 将程序jar包上传到指定目录 /etc/docker/my-dockerfile/docker-test;在该目录下新建Dockerfile文件image.png
  2. 编写Dockerfile文件

image.png 3. 使用命令制作镜像,镜像名为docker-test,tag为v3:"docker build -t docker-test:v3 ."

  1. 现在我要将这两个镜像跑起来,并且docker-test可以访问到redisimage.png
  2. 先使用"docker network create ocker-test-net"命令创建一个新的 Docker 网络,待会启动docker-test容器和redis容器时指定网络,才可以互相访问(这是其中的一种方式)
  3. 使用命令“docker run -d -p 6379:6379 --name redis-server --network docker-test-net redis”启动redis容器,指定容器名为“redis-server”
  4. 使用命令“docker run -p 80:80 --network docker-test-net docker-test:v3”启动docker-test容器,程序配置“spring.redis.host=redis-server”中指定了redis的host,使得其可以访问redis
  5. 最终跑起来的容器 image.png
  6. 访问http接口image.png

实操2: 简单使用compose同时编排程序和redis

  1. 准备工作如实操1
  2. 新增compose.yml文件

image.png

image.png 3.直接在当前目录使用命令"docker compose up",跑完后查看容器

image.png 4.访问http接口

image.png