为运行状况检查方法添加了更新的解决方案。简单代码段:
healthcheck:
test: out=$$(mysqladmin ping -h localhost -P 3306 -u foo
说明:由于mysqladmin ping
返回的是肯定的错误消息(尤其是输入错误的密码),因此我将输出保存到临时变量中,然后grep
用于查找预期的输出(mysqld is alive
)。如果找到,它将返回0错误代码。如果找不到它,我将打印整个消息,并返回1错误代码。
扩展代码段:
version: "3.8"
services:
db:
image: linuxserver/mariadb
environment:
- FILE__MYSQL_ROOT_PASSWORD=/run/secrets/mysql_root_password
- FILE__MYSQL_PASSWORD=/run/secrets/mysql_password
secrets:
- mysql_root_password
- mysql_password
healthcheck:
test: out=$$(mysqladmin ping -h localhost -P 3306 -u root
secrets:
mysql_root_password:
file: ${SECRETSDIR}/mysql_root_password
mysql_password:
file: ${SECRETSDIR}/mysql_password
说明:我使用的是docker secrets而不是env变量(但这也可以通过常规的env vars实现)。使用的$$
是文字$
符号,当传递到容器时会被剥离。
来自docker inspect --format "{{json .State.Health }}" db | jq
各种场合的输出:
一切都没事:
{
"Status": "healthy",
"FailingStreak": 0,
"Log": [
{
{
"Start": "2020-07-20T01:03:02.326287492+03:00",
"End": "2020-07-20T01:03:02.915911035+03:00",
"ExitCode": 0,
"Output": "mysqld is alive\n"
}
]
}
DB尚未启动(尚未):
{
"Status": "starting",
"FailingStreak": 1,
"Log": [
{
"Start": "2020-07-20T01:02:58.816483336+03:00",
"End": "2020-07-20T01:02:59.401765146+03:00",
"ExitCode": 1,
"Output": "\u0007mysqladmin: connect to server at 'localhost' failed error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2 \"No such file or directory\")' Check that mysqld is running and that the socket: '/var/run/mysqld/mysqld.sock' exists!\n"
}
]
}
密码错误:
{
"Status": "unhealthy",
"FailingStreak": 13,
"Log": [
{
"Start": "2020-07-20T00:56:34.303714097+03:00",
"End": "2020-07-20T00:56:34.845972979+03:00",
"ExitCode": 1,
"Output": "\u0007mysqladmin: connect to server at 'localhost' failed error: 'Access denied for user 'root'@'localhost' (using password: YES)'\n"
}
]
}