在 Docker 构建期间使用 .env 文件变量

Use .env file variables during Docker build

我正在尝试使用 sed 命令在 docker 构建期间替换变量。我试图做(开始)的变量是 $DATABASE_HOST。该值来自我的 .env 文件。我在网上读到,如果环境变量来自 .env 文件,则它们仅在 运行 时间内可用。因此,我的 sed 命令没有注册。

Docker 文件:

# Dockerfile for Sphinx SE
# https://hub.docker.com/_/alpine/
FROM alpine:3.12

# https://sphinxsearch.com/blog/
ENV SPHINX_VERSION 3.4.1-efbcc65

# Install dependencies
RUN apk add --no-cache mariadb-connector-c-dev \
    postgresql-dev \
    wget \
    sed

# set up and expose directories
RUN mkdir -pv /opt/sphinx/log /opt/sphinx/index
VOLUME /opt/sphinx/index

# http://sphinxsearch.com/downloads/sphinx-3.3.1-b72d67b-linux-amd64-musl.tar.gz
RUN wget http://sphinxsearch.com/files/sphinx-${SPHINX_VERSION}-linux-amd64-musl.tar.gz -O /tmp/sphinxsearch.tar.gz \
    && cd /opt/sphinx && tar -xf /tmp/sphinxsearch.tar.gz \
    && rm /tmp/sphinxsearch.tar.gz

# point to sphinx binaries
ENV PATH "${PATH}:/opt/sphinx/sphinx-3.4.1/bin"
RUN indexer -v

# redirect logs to stdout
RUN ln -sv /dev/stdout /opt/sphinx/log/query.log \
        && ln -sv /dev/stdout /opt/sphinx/log/searchd.log

# expose TCP port
EXPOSE 36307
EXPOSE 9306

# Copy base sphinx.conf file to container
VOLUME /opt/sphinx/conf
COPY ./sphinx.conf /opt/sphinx/conf/sphinx.conf

# Copy all docker sphinx.conf files
COPY ./configs/web-finder/docker/ /opt/sphinx/conf/

#  look for and replace
RUN sed -i "s+DATABASE_HOST+${DATABASE_HOST}+g" /opt/sphinx/conf/sphinx.conf

# Concat the sphinx.conf files for all apps
# RUN cat /tmp/myconfig.append >> /etc/portage/make.conf  && rm -f /tmp/myconfig.append

CMD indexer --all --config /opt/sphinx/conf/sphinx.conf \
    && searchd --nodetach --config /opt/sphinx/conf/sphinx.conf

.env 文件:

DATABASE_HOST=someport
DATABASE_USERNAME=someusername
DATABASE_PASSWORD=somepassword
DATABASE_SCHEMA=someschema
DATABASE_PORT=3306
SPHINX_PORT=36307

sphinx.conf:

searchd
{
  listen            = 127.0.0.1:$SPHINX_PORT
  log               = /opt/sphinx/searchd.log
  query_log         = /opt/sphinx/query.log
  read_timeout      = 5
  max_children      = 30
  pid_file          = /opt/sphinx/searchd.pid
  seamless_rotate   = 1
  preopen_indexes   = 1
  unlink_old        = 1
  binlog_path       = /opt/sphinx/
}

使用 sphinx,'sphinx.conf' 文件可以是 'executable'。也就是说,它实际上可以是 'shell script'(或 PHP、perl 等!)

假设您的 .env 文件在容器中生成真实的(运行时!)环境变量(对 Docker 不太熟悉),那么您的 sphinx.conf 文件可能是...

#!/bin/sh
set -eu
cat <<EOF
searchd
{
  listen            = 127.0.0.1:$SPHINX_PORT
  log               = /opt/sphinx/searchd.log
  query_log         = /opt/sphinx/query.log
  read_timeout      = 5
  max_children      = 30
  pid_file          = /opt/sphinx/searchd.pid
  seamless_rotate   = 1
  preopen_indexes   = 1
  unlink_old        = 1
  binlog_path       = /opt/sphinx/
}
EOF

因为它是一个 shell 脚本,所以变量会自动扩展 :)

也需要它可执行!

RUN chmod a+x /opt/sphinx/conf/sphinx.conf

那么根本不需要 Docker 文件中的 sed 命令!