Background: The development requires the crontab script to be executed in POD

Train of thought

  • Crond, vim, procps, crond, vim, procps, crond, vim, vim, procps

  • Crontab -e will create the /var/spool/cron/root file, and the script will be created in the file, so this will be done by the developer

  • Change the YAML file of K8S Deployment and add a container with a service image that will run crontab. In fact, there is no need to add another image. Cron can be executed through postStart in Lifecycle after the service container is started and crontab can also run. However, based on the per-process-per-container principle and the development need to see the log output from executing the script, I chose to add a new container

implementation

Dockerfile

/var/spool/cron/, but crontab is not executed at all. Only crontab/TMP /root can load scripts and run properly

FROM xxx COPY requirements.txt . COPY root /tmp/root RUN apt-get update && apt-get install cron vim procps libmariadb-dev-compat libmariadb-dev gcc -y; pip install --no-cache-dir \ -i https://pypi:[email protected]/ \ -r requirements.txt \ && rm requirements.txt ADD . /app WORKDIR /appCopy the code

deployment.yaml

Cron -f is the server for the foreground to run crontab. If you want to run it in a business container, you have to run cron because your service commands are executed by the foreground

Containers: containers: -image: XXX name: cron lifecycle: postStart: exec: command: - crontab - /tmp/root volumeMounts: - mountPath: /app/superconf.json name: superconf readOnly: true subPath: superconf.json command: - cron - -fCopy the code
  • Later, I wrote a simple script test and found no problem

Problems arise

UnicodeEncodeError: ‘ASCII’ codec can’t encode characters in position UnicodeEncodeError: ‘ASCII’ codec can’t encode characters in position Ordinal not in range(128) (similar) error, but entering the container to execute manually does work normally

This problem, looked up a lot of information, in this summary

    1. Add the Python variable PYTHONIOENCODING= UTF-8, for example: */1 * * * * PYTHONIOENCODING= UTF-8 python test.py. I’m sorry it didn’t work
    1. Add # encoding= UTF-8 or something like the following at the top of the Python file. Unfortunately, this is how Python2 works. Python3 defaults to UTF-8 encoding
import sys
reload(sys) 
sys.setdefaultencoding('utf-8')
Copy the code
    1. Crontab -e, add LANG=zh_CN. Utf-8 to the first line, unfortunately not useful either
    1. Source variable files, such as: */1 * * * * source file && python test.py, unfortunately useless
  • After some testing, I suddenly thought that since the terminal can run the script normally, there must be some dependent variable. Finally, ECHO $LANG, get C.UTF-8(based on the value of its own environment variable). After adding the environment variable at the end, the script executes normally */1 * * * * LANG= c.utf-8 python test.py.