【轉】docker-entrypoint.sh 文件的用處


參考出處
很多著名庫的 Dockerfile 文件中,通常都是 ENTRYPOINT 字段會是這樣:

ENTRYPOINT ["docker-entrypoint.sh"]


這里我們參考分析下 MySQL 的 Dockerfile 文件,來認識下 docker-entrypoint.sh 的用處。

MySQL 8.0 Dockerfile
網址:https://github.com/docker-library/mysql/tree/223f0be1213bbd8647b841243a3114e8b34022f4/8.0

里面的 Dockerfile 、 docker-entrypoint.sh 都寫了很多的 shell 代碼

這里通過 1 個例子,快速的了解 docker-entrypoint.sh 的使用方法

例子:MySQL 容器自建數據庫
網址:https://hub.docker.com/_/mysql/ 中,章節[ Initializing a fresh instance ] 中提到,可以在MySQL容器啟動時,初始化自定義數據庫:

When a container is started for the first time, a new database with the specified name will be created and initialized with the provided configuration variables. Furthermore, it will execute files with extensions .sh, .sql and .sql.gz that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order. You can easily populate your mysql services by mounting a SQL dump into that directory and provide custom images with contributed data. SQL files will be imported by default to the database specified by the MYSQL_DATABASE variable.

原理就是如下:

Dockerfile 中定義:

ENTRYPOINT ["docker-entrypoint.sh"]


docker-entrypoint.sh 中在啟動 mysql-server 前,創建數據庫:

ls /docker-entrypoint-initdb.d/ > /dev/null
for f in /docker-entrypoint-initdb.d/*; do
process_init_file "$f" "${mysql[@]}"
done

 

/docker-entrypoint-initdb.d/ 中文件哪里來呢?
可以像這樣:

FROM mysql:5.5
COPY db.sql /docker-entrypoint-initdb.d/

 

docker-entrypoint.sh 的用處
通過上述例子,可以清楚的看到,在啟動容器時,可以通過 shell 腳本執行些預處理邏輯,然后通過:

exec $@


把啟動容器入口正式交給使用者

即,需要容器啟動預處理的,都可以使用 docker-entrypoint.sh 機制

再舉個例子
比如本人遇到的一個項目,所以配置都在配置文件中,不走程序啟動參數,也不走環境變量設置的。

那么打成 docker 鏡像后,就是死配置了。

那么如何在不修改代碼的情況下,達成可變配置呢。

使用 docker-entrypoint.sh 即可達成目的。

比如如下這樣的 docker-entrypoint.sh :

#!/bin/bash
if [[ $redis_ip ]]; then
sed -i 's/redis_ip="[0-9.]*"/redis_ip="'$redis_ip'"/' config.ini
fi
if [[ $redis_port ]]; then
sed -i 's/redis_port="[0-9]*"/redis_port="'$redis_port'"/' config.ini
fi
echo "1" > /proc/sys/kernel/core_uses_pid
echo $CORE_PATH"/core-%e-%p-%t" > /proc/sys/kernel/core_pattern
exec "$@"

 



docker 啟動腳本如下:

docker run -d --restart=always \
--ulimit core=-1 --privileged=true\
-e redis_ip=$REDIS_IP \
-e redis_port=$REDIS_PORT \

 

以上,就可以達成自定義 redis ip/port ,並在啟動容器時,設置了 core 文件路徑與命名。

from:https://blog.csdn.net/u013272009/article/details/84073136


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM