简体   繁体   English

当 mysql docker 容器启动时,laravel 迁移数据库

[英]laravel migrate db when mysql docker container boots

When building a mysql container from docker-compose, once built is complete mysql takes few seconds before it comes alive.从 docker-compose 构建 mysql 容器时,一旦构建完成,mysql 需要几秒钟才能激活。 During this time I have a script that runs laravel migration.在此期间,我有一个运行 Laravel 迁移的脚本。 However it is impossible to connect to mysql for few seconds as it is still connecting (not sure exactly what it is doing).但是,几秒钟内无法连接到 mysql,因为它仍在连接(不确定它在做什么)。 To fix that I added in my script a sleep 30 which pauses for 30s while it waits for mysql container to fully come up live.为了解决这个问题,我在脚本中添加了sleep 30 ,它在等待 mysql 容器完全启动时暂停 30 秒。

I dont like this work around as it doesnt really fix the problem, what if next time I build the container it takes 31s?我不喜欢这项工作,因为它并没有真正解决问题,如果下次我构建容器需要 31 秒怎么办? then the laravel migration would still fail.那么 Laravel 迁移仍然会失败。

Has anyone has this problem migrating a fresh (just booted) mysql database container?有没有人在迁移一个新的(刚刚启动的)mysql 数据库容器时遇到这个问题? any ideas how I could fix this?有什么想法可以解决这个问题吗?

I'm not exactly sure about your docker configuration but as a linux user I would use netcat to test the TCP Connection.我不太确定您的 docker 配置,但作为 linux 用户,我会使用 netcat 来测试 TCP 连接。 (On debian/ubuntu: apt install netcat) (在 debian/ubuntu 上:apt install netcat)

To get the container IP, you could use:要获取容器 IP,您可以使用:

containerIP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id)

And then wait for the connection with netcat然后等待与netcat的连接

nc -w 45 -v $containerIP 3306 </dev/null

The -w sets the timeout you want -w 设置你想要的超时时间

So you can run your migrate or do something else if it's failed.因此,如果迁移失败,您可以运行迁移或执行其他操作。

if [ $? -eq 0 ]; then
    echo "Run your migrate"
else
    echo "Unable to connect"
fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM