如果您已经启动了MySQL,并且暴露了端口,那么您应该能够通过连接来访问它
localhost
,带端口
3306
否则,正如你所建议的,有可能建立一个
docker-compose file
version: '3.3'
services: # list of services composing your application
db: # the service hosting your MySQL instance
image: mysql:5.7 # the image and tag docker will pull from docker hub
volumes: # this section allows you to configure persistence within multiple restarts
- db_data:/var/lib/mysql
restart: always # if the db crash somehow, restart it
environment: # env variables, you usually set this to override existing ones
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: todoservice
MYSQL_USER: root
MYSQL_PASSWORD: root
todoservice: # you application service
build: ./ # this tells docker-compose to not pull from docker hub, but to build from the Dockerfile it will find in ./
restart: always
depends_on: # set a dependency between your service and the database: this means that your application will not run if the db service is not running, but it doesn't assure you that the dabase will be ready to accept incoming connection (so your application could crash untill the db initializes itself)
- db
volumes:
db_data: # this tells docker-compose to save your data in a generic docker volume. You can see existing volumes typing 'docker volume ls'
要启动和部署应用程序,现在需要键入终端:
docker-compose up
这将启动您的部署。请注意,这里没有暴露任何端口:只有您的服务才能从中访问数据库
db:3306
(您不需要通过IP引用,但可以使用服务名称访问其他服务)。
image
:
ports:
- "3306:3306"
请注意,此端口必须是免费的(没有其他系统服务使用它),否则整个部署将失败。
最后一点注意:由于docker compose会尽量避免在每次启动服务时构建图像,因此要强制它构建一个新的图像,您必须附加它
--build
码头工人组装
命令。
docker-compose down
. 要删除与部署相关的所有持久性数据(即从新数据库开始),请附加
-v
上一个命令末尾的标志。
希望有帮助!