# --- Stage 1: build nginx ---
FROM alpine:3.22 AS builder

ENV NGINX_VERSION=1.29.3

RUN apk add --no-cache \
        gcc make libc-dev pcre2-dev zlib-dev openssl-dev linux-headers curl gnupg tar

WORKDIR /tmp
RUN curl -fSL https://nginx.org/download/nginx-$NGINX_VERSION.tar.gz -o nginx.tar.gz \
 && tar -zxf nginx.tar.gz \
 && cd nginx-$NGINX_VERSION \
 && ./configure \
      --prefix=/etc/nginx \
      --sbin-path=/usr/sbin/nginx \
      --modules-path=/usr/lib/nginx/modules \
      --conf-path=/etc/nginx/nginx.conf \
      --error-log-path=/var/log/nginx/error.log \
      --http-log-path=/var/log/nginx/access.log \
      --pid-path=/var/run/nginx.pid \
      --lock-path=/var/run/nginx.lock \
      --with-http_ssl_module \
      --with-http_v2_module \
      --with-http_gzip_static_module \
 && make && make install

# --- Stage 2: runtime ---
FROM alpine:3.22

RUN apk add --no-cache pcre2 zlib openssl ca-certificates wget \
 && adduser -D -g 'nginx' nginx \
 && mkdir -p /var/cache/nginx /etc/nginx/conf.d /usr/share/nginx/html \
 && chown -R nginx:nginx /var/cache/nginx /var/run /etc/nginx /usr/share/nginx/html

COPY --from=builder /usr/sbin/nginx /usr/sbin/nginx
COPY --from=builder /etc/nginx /etc/nginx
COPY --from=builder /usr/lib/nginx /usr/lib/nginx
COPY nginx.conf /etc/nginx/nginx.conf

EXPOSE 80 443
STOPSIGNAL SIGTERM
CMD ["nginx", "-g", "daemon off;"]

HEALTHCHECK --interval=30s --timeout=3s --retries=3 CMD wget -qO- http://127.0.0.1:80/ || exit 1
