我需要用ubuntu和mysql(不是单独的容器(创建docker文件
当我添加时
apt-get install -y mysql-server
码头文件
安装程序创建var/lib/mysql并将数据放在这里。
所以当我在docker中配置它时,编写
volumes:
- ./var/mysql:/var/lib/mysql
并在入口点尝试创建数据库
/usr/bin/mysql -u root -e "CREATE DATABASE IF NOT EXISTS ${MYSQL_DATABASE};"
/usr/bin/mysql -u root -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY '${MYSQL_ROOT_PASSWORD}';"
/var/mysql为空direcorymysql不启动
那么如何正确地做呢?
您希望将Ubuntu和MySQL合并到一个Docker容器中。
但最好的方法是按原样使用Docker,将这类应用程序拆分到自己的容器中。创建一个Ubuntu容器en创建一个MySQL容器,并允许Ubuntu访问MySQL。
参见以下示例:
docker-compase.yml
在文件夹中创建一个docker-compose.yml。
version: '3.9'
services:
ubuntu:
build: .
image: ubuntusql
container_name: ubuntu
command: ["sleep", "300d"]
mysqlcontainer:
image: mysql
container_name: mysql
environment:
MYSQL_ROOT_PASSWORD: example
volumes:
- ./database:/var/lib/mysql
- ./mysql_init:/docker-entrypoint-initdb.d
ports:
- "33060:33060"
- "3306:3306"
dockerfile
在同一个文件夹中,创建一个Dockerfile来创建自己的Ubuntu映像。
创建自己的映像的原因是您希望在Ubuntu 中提供mysql_client
FROM ubuntu
WORKDIR /root
RUN apt-get update && apt-get upgrade
&& apt-get --assume-yes install mysql-client
mysql_init.shql
创建一个名为mysql_init的子文件夹,并在其中创建一个mysql_init.sql文件。(请参阅docker-compose.yml,它希望该文件可用(
CREATE DATABASE IF NOT EXISTS exampledb;
USE exampledb;
CREATE USER dbuser IDENTIFIED BY 'dbpassword';
GRANT ALL PRIVILEGES ON exampledb.* TO dbuser ;
CREATE TABLE contacts (
name VARCHAR(255),
address VARCHAR(255)
);
INSERT INTO contacts (name, address) VALUES ('John', 'Street');
INSERT INTO contacts (name, address) VALUES ('Mary', 'Another Street');
INSERT INTO contacts (name, address) VALUES ('Donald', 'No Street');
数据库文件夹
创建名为"数据库"的子文件夹。docker-compose.yml期望它在那里,MySQL docker容器将在该文件夹中创建数据库。
启动docker compose
docker compose up
从ubuntu进行测试
输入Ubuntu容器:
docker exec -it ubuntu /bin/bash
在Ubuntu容器中,启动MySQL并检查是否可以访问MySQL数据库和数据
$ docker exec -it ubuntu /bin/bash
root@10c8ef06a399:~# mysql -h mysql -u dbuser -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 9
Server version: 8.0.25 MySQL Community Server - GPL
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.
mysql> use exampledb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> show tables;
+---------------------+
| Tables_in_exampledb |
+---------------------+
| contacts |
+---------------------+
1 row in set (0.00 sec)
mysql> select * from contacts;
+--------+----------------+
| name | address |
+--------+----------------+
| John | Street |
| Mary | Another Street |
| Donald | No Street |
+--------+----------------+
3 rows in set (0.01 sec)
mysql> exit
Bye
root@10c8ef06a399:~# exit
exit
$