# stage 1: 构建阶段
FROM alpine:3.21.3 AS builder
 
ARG OPENRESTY_VERSION=1.27.1.2
 
# 替换为阿里云源并安装构建依赖
RUN sed -i 's|https://dl-cdn.alpinelinux.org/alpine|https://mirrors.aliyun.com/alpine|g' /etc/apk/repositories && \
    apk add --no-cache \
    build-base \
    pcre-dev \
    openssl-dev \
    zlib-dev \
    perl \
    linux-headers
 
# 拷贝并解压 OpenResty 源码
WORKDIR /tmp
RUN wget https://openresty.org/download/openresty-${OPENRESTY_VERSION}.tar.gz && \
    tar zxpf openresty-${OPENRESTY_VERSION}.tar.gz && \
    sed -i '/^#define NGX_MAX_ERROR_STR/s/4096/2048000/g' openresty-${OPENRESTY_VERSION}/bundle/nginx-1.27.1/src/core/ngx_log.h
 
# 编译安装 OpenResty
WORKDIR /tmp/openresty-${OPENRESTY_VERSION}
RUN ./configure --prefix=/usr/local/openresty \
                --with-pcre-jit \
                --with-http_ssl_module \
                --with-http_v2_module \
                --with-http_realip_module \
                --with-http_stub_status_module \
                -j2 && \
    make && \
    make install
 
# 剥离可执行文件
RUN strip /usr/local/openresty/nginx/sbin/nginx
 
# stage 2: 最终运行环境
FROM alpine:3.21.3
 
# 安装运行时依赖
 
# 安装运行时依赖与时区支持
RUN sed -i 's|https://dl-cdn.alpinelinux.org/alpine|https://mirrors.aliyun.com/alpine|g' /etc/apk/repositories && \
    apk add --no-cache \
    libgcc \
    pcre \
    openssl \
    zlib \
    tzdata && \
    cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
    echo "Asia/Shanghai" > /etc/timezone
 
# 复制编译好的 OpenResty 文件
COPY --from=builder /usr/local/openresty /usr/local/openresty
 
# 设置工作目录和环境变量
WORKDIR /usr/local/openresty
ENV PATH "/usr/local/openresty/bin:/usr/local/openresty/nginx/sbin:$PATH"

# 暴露端口
EXPOSE 80
 
# 启动命令
CMD ["nginx", "-g", "daemon off;"]
