2

Asp-Net-Core开发笔记:使用alpine镜像并加入健康检查 - 程序设计实验室

 2 weeks ago
source link: https://www.cnblogs.com/deali/p/18147029
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

前言#

使用 docker 部署 AspNetCore 应用已经是标配了,之前我一直使用 mcr.microsoft.com/dotnet/aspnet:8.0 这类镜像,简单粗暴,不过可以使用 alpine 进一步优化镜像大小。

很多开源工具的 docker 都有健康检查,这次我顺便也给加上了。

PS: 本文的例子项目来自一个差点被砍掉的项目「IdentityServerLite」,后面我会写个文章介绍一下~

添加健康检查#

builder.Services.AddHealthChecks();

配置中间件

app.MapHealthChecks("/healthz");

之后测试一下,本地运行后访问 http://host:port/healthz 可以看到 Healthy 字样

修改 docker-compose#

在应用配置下面增加 healthcheck 配置

这个镜像 mcr.microsoft.com/dotnet/aspnet 里自带了 wget ,所以直接用这个来请求健康检查接口就完事了,如果用 curl 还得去安装。

version: '3.6'

services:
  web:
    image: ${DOCKER_REGISTRY-}web
    container_name: ids-lite
    restart: always
    environment:
      - ASPNETCORE_ENVIRONMENT=Production
      - ASPNETCORE_URLS=http://+:80
    build:
      context: .
    volumes:
      - .:/app
    networks:
      - swag
    healthcheck:
      test: ["CMD-SHELL", "wget --spider http://localhost:80/healthz || exit"]
      interval: 10s
      timeout: 5s
      retries: 5

networks:
  swag:
    name: swag
    external: true

换成 alpine 基础镜像#

还没有配置CICD之前,我使用了 FrameworkDependent 的方式来搭配 docker 部署,详见之前的文章: Asp-Net-Core开发笔记:FrameworkDependent搭配docker部署

换成 alpine 可以减少一半镜像体积,从 240MB 减少到 100MB 左右。

修改 dockerfile

8.0 后面加 -alpine 就行了

FROM mcr.microsoft.com/dotnet/aspnet:8.0-alpine AS base
RUN apk add --no-cache icu-libs
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM base AS final
WORKDIR /app
COPY . .
ENTRYPOINT ["./IdsLite.Api"]

ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

重新发布#

之前在本机发布的时候,运行时选的是 linux-x64

这样发布出来的可执行文件是依赖 glibc 的

但是 alpine 基础镜像里是 musl libc

所以需要选择 linux-musl-x64 这个运行时,然后重新发布

dotnet publish -r linux-musl-x64

参考资料#

微信公众号:「程序设计实验室」 专注于互联网热门新技术探索与团队敏捷开发实践,包括架构设计、机器学习与数据分析算法、移动端开发、Linux、Web前后端开发等,欢迎一起探讨技术,分享学习实践经验。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK