Dockerfile Tips

Dockerfile 编写建议

日常编写Dockerfile的过程中总结的一些经验:

  • 基础镜像尽量选择alpine版本,减小镜像体积,如果需要glibc,在Dockerfile中添加以下指令

    RUN apk --no-cache add ca-certificates wget && \
        wget -q -O /etc/apk/keys/sgerrand.rsa.pub https://alpine-pkgs.sgerrand.com/sgerrand.rsa.pub && \
        wget https://github.com/sgerrand/alpine-pkg-glibc/releases/download/2.29-r0/glibc-2.29-r0.apk && \
        apk --no-cache add glibc-2.29-r0.apk

    关于在alpine镜像中安装glibc,详情可以参考 github 介绍

  • Dockerfile里需要安装软件的尽量使用国内的源,加快ci构建,常见的操作如下:

    • alpine:
    RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
    • debian:
    curl -L "https://mirrors.ustc.edu.cn/repogen/conf/debian-https-4-buster" -o /etc/apt/sources.list
    • centos:
    RUN curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
    • node:
    RUN npm install --registry=https://registry.npm.taobao.org \
        && npm config set phantomjs_cdnurl https://npm.taobao.org/dist/phantomjs \
        && npm config set chromedriver_cdnurl http://cdn.npm.taobao.org/dist/chromedriver \
        && npm config set sass_binary_site http://npm.taobao.org/mirrors/node-sass
  • 构建镜像时如果需要代理,可以配置以下参数:

    docker build -t imagename . --build-arg HTTP_PROXY=http://ip:port --build-arg HTTPS_PROXY=http://ip:port
  • apt-get 命令可以通过以下参数临时设置代理:

    RUN apt update -o Acquire::http::proxy="http://ip:port" -o Acquire::https::proxy="http://ip:port" && \
        apt install --yes curl -o Acquire::http::proxy="http://ip:port" -o Acquire::https::proxy="http://ip:port"
  • 镜像设置北京时间,可以安装tzdata软件包,再设置/etc/localtime:

    RUN apk add tzdata && ln -sfv /usr/share/zoneinfo/Asia/Shanghai /etc/localtime 
  • 如果容器中文显示乱码,可以在Dockerfile中配置LANG环境变量:

    ENV LANG C.UTF-8

Thu Jun 13, 2019 cheon