docker-entrypoint.sh文件的用處詳解
參考出處:
很多著名庫的 Dockerfile 文件中,通常都是 ENTRYPOINT 字段會是這樣:
ENTRYPOINT ["docker-entrypoint.sh"]
這里我們參考分析下 MySQL 的 Dockerfile 文件,來認識下 docker-entrypoint.sh 的用處。
MySQL 8.0 Dockerfile
里面的 Dockerfile 、 docker-entrypoint.sh 都寫了很多的 shell 代碼
這里通過 1 個例子,快速的了解 docker-entrypoint.sh 的使用方法
例子:MySQL 容器自建數(shù)據(jù)庫
網(wǎng)址:https://hub.docker.com/_/mysql/ 中,章節(jié)[ Initializing a fresh instance ] 中提到,可以在MySQL容器啟動時,初始化自定義數(shù)據(jù)庫:
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 前,創(chuàng)建數(shù)據(jù)庫:
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 腳本執(zhí)行些預處理邏輯,然后通過:
exec $@
把啟動容器入口正式交給使用者
即,需要容器啟動預處理的,都可以使用 docker-entrypoint.sh 機制
再舉個例子
比如本人遇到的一個項目,所以配置都在配置文件中,不走程序啟動參數(shù),也不走環(huán)境變量設置的。
那么打成 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 \ xxx
以上,就可以達成自定義 redis ip/port ,并在啟動容器時,設置了 core 文件路徑與命名。
總結
當然,這些僅為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
項目訪問使用docker bridge網(wǎng)絡模式(端口映射)配置過程
這篇文章主要介紹了項目訪問使用docker bridge網(wǎng)絡模式(端口映射)配置過程,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-03-03docker搭建lnmp環(huán)境的實現(xiàn)步驟
DNMP(Docker + Nginx + MySQL + PHP7/5 + Redis)是一款全功能的LNMP一鍵安裝程序,本文就來介紹一下docker搭建lnmp環(huán)境的實現(xiàn)步驟,具有一定的參考價值,感興趣的可以了解一下2024-07-07把數(shù)據(jù)庫部署在docker容器內(nèi)有哪些缺陷
這篇文章主要介紹了把數(shù)據(jù)庫部署在docker容器內(nèi)有哪些缺陷,幫助大家更好的理解和學習docker容器和數(shù)據(jù)庫,感興趣的朋友可以了解下2020-08-08在CentOS啟動時自動加載內(nèi)核模塊overlayfs操作
這篇文章主要介紹了在CentOS啟動時自動加載內(nèi)核模塊overlayfs操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11Ubuntu 20.04 上安裝和使用 Docker的詳細過程(安裝包)
這篇文章主要介紹了Ubuntu 20.04 上安裝和使用 Docker的詳細過程(安裝包),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03