Unable to execute .sh file in crontab docker

2019-08-30 04:21发布

问题:

I am working on a project which is on Docker, Crontab, Python & CentOS. I have a requirement to read docker compose environment variables in Python script.

I have the below Docker File, Crontab and Shell Wrapper files

Docker file

FROM centos:latest

RUN yum -y install crontabs

RUN yum update -y \
    && yum install -y https://centos7.iuscommunity.org/ius-release.rpm \
    && yum install -y python36u python36u-libs python36u-devel python36u-pip \
    && yum install -y which gcc \ 
    && yum install -y openldap-devel  

# pipenv installation
RUN pip3.6 install pipenv
RUN ln -s /usr/bin/pip3.6 /bin/pip
RUN rm /usr/bin/python
# python must be pointing to python3.6
RUN ln -s /usr/bin/python3.6 /usr/bin/python

RUN pip install --upgrade pip  
RUN pip install pymysql
RUN pip install pymongo
RUN pip install lxml
RUN pip install pyyaml
RUN pip install envs

# comment out PAM
RUN sed -i -e '/pam_loginuid.so/s/^/#/' /etc/pam.d/crond

RUN printenv | grep -v "MAINDB_CONNECTIONSTRING" > /root/project_env.sh

ENV SCRIPT_DIR="/opt/Importer"
WORKDIR ${SCRIPT_DIR}
COPY Importer/* ./

#Add your cron file
ADD Importer/crontab /etc/cron.d/crontab
RUN chmod 0644 /etc/cron.d/crontab
RUN chmod +x /opt/Importer/ShellWrapper.sh

#This will add it to the cron table (crontab -e)
RUN crontab /etc/cron.d/crontab

# Create the log file to be able to run tail
RUN touch /var/log/cron.log

CMD crond && tail -f /var/log/cron.log

Crontab file

#!/bin/bash
* * * * * /usr/bin/sh /opt/Importer/ShellWrapper.sh
# Mandatory blank line

ShellWrapper.sh

#/bin/bash
/usr/bin/python Importer.py

Actual result - When I execute the ShellWrapper.sh in docker /bin/bash directly, the python script is being executed but the same ShellWrapper.sh is not being executed with Crontab.

Expected result - Crontab should execute ShellWrapper.sh and ShellWrapper.sh file will execute Python script

Could you please help on this?

回答1:

In cron.d, you need to specify the user:

* * * * * root /usr/bin/sh /opt/Importer/ShellWrapper.sh

See also: similar questions on using the cron.d folder