如何使用 start 在 alpine docker 容器中加载 shell 别名

How to load shell aliases in an alpine docker container with start

我已经写了一个 DOCKER 文件,它使用一个私有的改编的 alpine 图像作为图像,其中包含一个 nginx 服务器。 注意:alpine 使用的是 zsh,不是 bash.

我喜欢有一些可用的 shell 别名,当在容器中工作时,当它们丢失时,这让我抓狂。所以我将一个准备好的小文件复制到 /root/.profile,这很有效。我可以查看文件及其内容。但是只有当我手动执行时,文件才会加载。 ~/.profile 在容器中然后我有可用的别名。

我需要做什么,在我启动容器并连接到它后自动加载我的配置文件 shell?

FROM myprivatealpineimage/base-image-php:7.4.13

ARG TIMEZONE

COPY ./docker/shared/bashrc /root/.profile

COPY ./docker/shared/ /tmp/scripts/
RUN chmod +x -R /tmp/scripts/ \
    && /tmp/scripts/set_timezone.sh ${TIMEZONE}\
    && apk update\
    && apk add --no-cache git

RUN install-ext pecl/apcu pecl/imagick pecl/zip pecl/redis
RUN apk add --no-cache --repository http://dl-3.alpinelinux.org/alpine/edge/testing gnu-libiconv
ENV LD_PRELOAD /usr/lib/preloadable_libiconv.so php

WORKDIR /var/www

将您的文件复制为 .bashrc 文件到您的用户目录下:

COPY docker/shared/bashrc /home/{YOUR_USER}/.bashrc

您可以在 docker 构建期间添加别名,如下所示:

# Making our command line life a little easier...
RUN echo 'alias ll="ls -l"' >> ~/.bashrc
RUN echo 'alias la="ls -la"' >> ~/.bashrc

这似乎有效:

FROM myprivatealpineimage/base-image-php:8.0.3

ARG TIMEZONE
ARG WITH_XDEBUG=false

COPY ./docker/shared/bashrc /root/.profile
COPY ./docker/shared/bashrc /root/.ashrc

COPY ./docker/shared/ /tmp/scripts/
RUN chmod +x -R /tmp/scripts/ \
    && /tmp/scripts/set_timezone.sh ${TIMEZONE} \
    && apk add --no-cache git  

WORKDIR /var/www

我刚刚重新构建我的容器,当我登录时,我有了我的别名。如果有人可以确认此设置有效,我会将其标记为正确答案。不知道为什么它有效而另一个没有。

对我来说,这很有效:

  1. 为每个别名创建一个 shell 脚本。例如,backup.shcompile.shdblogin.sh.

  2. 将所有这些脚本放在一个目录中。例如scripts

  3. 将该目录添加到 Dockerfile 内的 PATH 环境变量中。示例:

    ENV PATH="${PATH}:/temp/scripts"

  4. 将此目录装载到您的 docker-compose.yml 文件中。示例:

        volumes: 
            - /path/to/scripts/on/local/machine:/temp/scripts
  1. 确保您添加到 PATH 的路径与您在 docker-compose.yml 中装载的路径相匹配。例如两者都应该是 /temp/scripts

  2. 现在在您的 docker 交互式 shell 中,您可以简单地使用脚本文件的名称调用脚本文件,例如 compiledblogin

默认 docker 启动 non-login shell。 要阅读 .profile 文件,您需要登录 shell docker exec -it <container> ash -l.

要每次读取/etc/profile(或另一个启动文件),您必须设置 ENV 变量。

示例 Dockerfile

ARG PHPVERSION=7.4
FROM php:$PHPVERSION-fpm-alpine

ARG PHPVERSION=7.4
ENV PHPVERSION_ENV=$PHPVERSION

# copy composer from official image
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

#set $ENV
ENV ENV=/etc/profile
#copy aliases definition
COPY /assets/alias.sh /etc/profile.d/alias.sh