2020年12月16日 星期三

[Dockerfile] Trouble shooting - cannot get environment variables and permission denied on Entrypoint

 

 Docker   Dockerfile   sudo  

 

 

Problem


 

We have a Dockerfile that will switch user to run a shell script on ENTRYPOINT, however we got the 2 problems,

 

1.  Cannot get the environment variables in the shell script.

2.  Get permission denied after we preserve the environment variables when sudo user.

 

Here are the sample files,

 

Dockerfile

FROM postgres:11

ENV POSTGRES_USER postgres
ENV POSTGRES_PASSWORD xxxxx

# Add user: postgres
RUN sudo adduser postgres sudo

EXPOSE 5432
ENTRYPOINT ["/bin/sh""-c""sudo -u postgres sh callback.sh"]


 

Shell script (callback.sh)

#!/bin/bash echo POSTGRES_USER=$POSTGRES_USER
echo POSTGRES_PASSWORD=$POSTGRES_PASSWORD
echo "some logs" >> ~/my_log

The container from the above Dockerfile could not get the environment variables $POSTGRES_USER and $POSTGRES_PASSWORD, and finally output,

 

POSTGRES_USER=

POSTGRES_PASSWORD=

 

And the log file will be located at /var/lib/postgresql/my_log.

 

 

Environment


 

Docker desktop 2.3.0.3

 

 

 

Solution


 

Preserving environment variables

 

The problem was due to not preserving environment variables when switching to other user.

 

So we have to preserve the existing environment variables by adding the argument -U when sudo. (See sudo manual)

 

-E, --preserve-env: Indicates to the security policy that the user wishes to preserve their existing environment variables. The security policy may return an error if the user does not have permission to preserve the environment.

 

So we must update the following line of Dockerfile,

ENTRYPOINT ["/bin/sh""-c""sudo -E -u postgres sh callback.sh"]

 

But it caused the second problem: Permission denied when writing log to ~/my_log.

The output became as following,

 

POSTGRES_USER=postgres

POSTGRES_PASSWORD=xxxxx

callback.sh: 3: callback.sh: cannot create /root/my_log: Permission denied

 

 

As you can see the ~/ is changed to /root/ but not /var/lib/postgresql/, so that the user: postgres could not have the permission on ~/.

 

Finally I solved the problems by updating the Dockerfile as following,

 

 

Dockerfile

FROM postgres:11

ENV POSTGRES_USER postgres
ENV POSTGRES_PASSWORD xxxxx

 
# Add user: postgres
RUN sudo adduser postgres sudo

EXPOSE 5432
ENTRYPOINT ["/bin/sh""-c""sudo -E -u postgres sh callback.sh"]

# Or use this # ENTRYPOINT ["/bin/sh", "-c", "su --preserve-environment - postgres callback.sh'"]


 

Shell script (callback.sh)

#!/bin/bash echo POSTGRES_USER=$POSTGRES_USER echo POSTGRES_PASSWORD=$POSTGRES_PASSWORD echo "some logs" >> /var/lib/postgresql/my_log

 

沒有留言:

張貼留言