使用wait-for-it.sh触发Node.js语法错误,需实现MySQL就绪后启动后端
问题原因
Node.js尝试执行shell脚本wait-for-it.sh导致语法错误。核心原因是Node镜像默认ENTRYPOINT为node,当你用Docker Compose数组格式的command时,./wait-for-it.sh会被当作参数传给node,而非由shell执行。
解决方案
方案1:修改Docker Compose的command为shell执行格式
将后端服务的command改为以下形式,明确指定用shell运行脚本:
command: sh -c "wait-for-it.sh database-mysql:3306 -- node dist/main.js"
说明:
sh -c指令让容器用shell解析并执行后续命令- 你已经在Dockerfile中将
wait-for-it.sh放到/usr/local/bin目录,该目录在系统PATH中,因此可以直接调用脚本,无需写相对路径
方案2:用数组格式指定shell执行器
如果偏好Docker Compose的数组命令格式,可改为:
command: ["/bin/sh", "-c", "wait-for-it.sh database-mysql:3306 -- node dist/main.js"]
额外检查项
- 确认
wait-for-it.sh的shebang行兼容Alpine系统:脚本开头需为#!/bin/sh(Alpine默认使用ash shell,兼容sh语法) - 你已在Dockerfile中执行
chmod +x /usr/local/bin/wait-for-it.sh,脚本的可执行权限已配置到位,无需额外操作
补充说明
depends_on仅保证容器启动顺序,无法确保MySQL服务完成初始化。wait-for-it.sh的作用就是等待MySQL端口就绪,解决服务启动的时序问题。修改后,后端会在确认MySQL端口可用后,再启动Node服务。
内容的提问来源于stack exchange,提问作者Tai Le
相关产品推荐
相关产品推荐

