docker-compose down -v 将删除命名卷,但它不会删除您作为绑定挂载(如在您的配置中)挂载的目录。为此,您需要自己使用rm -rf。
如果您希望docker-compose 管理卷,请改用命名卷:
version: "3.7"
services:
my-main-db:
env_file:
- .env
image: mysql:8
container_name: my-main-db
command: --default-authentication-plugin=mysql_native_password
restart: always
ports:
- 3306:3306
environment:
MYSQL_ROOT_PASSWORD: $MY_SERVICE_DB_ROOT_PASSWORD
MYSQL_DATABASE: my_service_db_local
MYSQL_USER: $MY_SERVICE_DB_APP_USER
MYSQL_PASSWORD: $MY_SERVICE_DB_APP_PASSWORD
volumes:
- my-service-db-data:/var/lib/mysql
volumes:
my-service-db-data:
这将在启动堆栈时自动为您分配一个 docker 卷,并在您运行 docker-compose down -v 时将其删除。
例如,如果我在.env 中有以下内容:
MY_SERVICE_DB_ROOT_PASSWORD=secret
MY_SERVICE_DB_APP_USER=myservice
MY_SERVICE_DB_APP_PASSWORD=secret
我可以调出堆栈:
docker-compose up -d
然后连接mysql并建表:
$ mysql -h docker -u myservice -psecret my_service_db_local
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.23 MySQL Community Server - GPL
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MySQL [my_service_db_local]> create table testtable (id int);
Query OK, 0 rows affected (0.065 sec)
MySQL [my_service_db_local]> show tables;
+-------------------------------+
| Tables_in_my_service_db_local |
+-------------------------------+
| testtable |
+-------------------------------+
1 row in set (0.004 sec)
MySQL [my_service_db_local]> ^DBye
现在,如果我使用 -v 降低堆栈:
$ docker-compose down -v
Stopping my-main-db ... done
WARNING: Found orphan containers (docker_test_1) for this project. If you removed or renamed this service in your compose file, you can run this command with the --remove-orphans flag to clean it up.
Removing my-main-db ... done
Removing network docker_default
Removing volume docker_my-service-db-data
...你可以看到Docker已经删除了docker_my-service-db-data
体积。如果我们重新启动堆栈:
$ docker-compose up -d
Creating network "docker_default" with the default driver
Creating volume "docker_my-service-db-data" with default driver
WARNING: Found orphan containers (docker_test_1) for this project. If you removed or renamed this service in your compose file, you can run this command with the --remove-orphans flag to clean it up.
Creating my-main-db ... done
我们可以连接mysql,看到表已经不存在了,
因为数据库是从头开始重新创建的:
$ mysql -h docker -u myservice -psecret my_service_db_local
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.23 MySQL Community Server - GPL
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MySQL [my_service_db_local]> show tables;
Empty set (0.004 sec)
MySQL [my_service_db_local]>