[英]Dockerfile: $HOME is not working with ADD/COPY instructions
在提交錯誤之前,我想請人確認我最近遇到的奇怪的docker build
行為。
考慮我們有一個簡單的 Dockerfile,我們試圖將一些文件復制到非 root 用戶的主目錄中:
FROM ubuntu:utopic
ENV DEBIAN_FRONTEND=noninteractive
RUN sed -i.bak 's/http:\/\/archive.ubuntu.com\/ubuntu\//mirror:\/\/mirrors.ubuntu.com\/mirrors.txt\//g' /etc/apt/sources.list
RUN echo "deb http://repo.aptly.info/ squeeze main" >> /etc/apt/sources.list.d/_aptly.list
RUN apt-key adv --keyserver keys.gnupg.net --recv-keys e083a3782a194991
RUN apt-get update
RUN apt-get install -y aptly
RUN useradd -m aptly
RUN echo aptly:aptly | chpasswd
USER aptly
COPY ./.aptly.conf $HOME/.aptly.conf
COPY ./public.key $HOME/public.key
COPY ./signing.key $HOME/signing.key
RUN gpg --import $HOME/public.key $HOME/signing.key
RUN aptly repo create -comment='MAILPAAS components' -distribution=utopic -component=main mailpaas
CMD ["/usr/bin/aptly", "api", "serve"]
這就是我嘗試構建此映像時得到的結果:
...
Step 10 : USER aptly
---> Running in 8639f826420b
---> 3242919b2976
Removing intermediate container 8639f826420b
Step 11 : COPY ./.aptly.conf $HOME/.aptly.conf
---> bbda6e5b92df
Removing intermediate container 1313b12ca6c6
Step 12 : COPY ./public.key $HOME/public.key
---> 9a701a78d10d
Removing intermediate container 3a6e40b8593a
Step 13 : COPY ./signing.key $HOME/signing.key
---> 3d4eb847abe8
Removing intermediate container 5ed8cf52b810
Step 14 : RUN gpg --import $HOME/public.key $HOME/signing.key
---> Running in 6e481ec97f74
gpg: directory `/home/aptly/.gnupg' created
gpg: new configuration file `/home/aptly/.gnupg/gpg.conf' created
gpg: WARNING: options in `/home/aptly/.gnupg/gpg.conf' are not yet active during this run
gpg: keyring `/home/aptly/.gnupg/secring.gpg' created
gpg: keyring `/home/aptly/.gnupg/pubring.gpg' created
gpg: can't open `/home/aptly/public.key': No such file or directory
gpg: can't open `/home/aptly/signing.key': No such file or directory
gpg: Total number processed: 0
似乎$HOME
是空的。 但為什么? 將絕對路徑放在 home 目錄而不是$HOME
不是很方便。
這是你的問題:
當您使用USER
指令時,它會影響用於在容器內啟動新命令的用戶 ID。 因此,例如,如果您這樣做:
FROM ubuntu:utopic
RUN useradd -m aptly
USER aptly
RUN echo $HOME
你得到這個:
Step 4 : RUN echo $HOME
---> Running in a5111bedf057
/home/aptly
因為RUN
命令在容器內啟動一個新的 shell,它由前面的USER
指令修改。
當您使用COPY
指令時,您並不是在容器內啟動進程,並且 Docker 無法知道 shell 會公開哪些(如果有)環境變量。
您最好的選擇是在您的 Dockerfile 中設置ENV HOME /home/aptly
aptly,這將起作用,或者將您的文件暫存到一個臨時位置,然后:
RUN cp /skeleton/myfile $HOME/myfile
另外,請記住,當您COPY
文件時,它們將由root
擁有; 你將需要明確chown
他們到相應的用戶。
根據Docker 文檔, USER
僅適用於RUN
、 CMD
和ENTRYPOINT
。
USER
指令設置用戶名(或 UID)和可選的用戶組(或 GID)以在運行映像時使用,以及在ENTRYPOINT
中跟在它ENTRYPOINT
任何RUN
、CMD
和ENTRYPOINT
指令。
您需要使用絕對路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.