如何在数据库Docker容器中创建数据库?

如何在数据库Docker容器中创建数据库?

问题描述:

我是docker的新手,所以无法理解-如果我要构建mysql/postgresql/clickhouse等容器-如何创建数据库和数据库/表架构?也许在Dockerfile中或者我可以从docker-compose.yml中做到这一点?

I'm new in docker, so cant understand - if I want to build container of mysql/postgresql/clickhouse etc - how to create database and schema of database/table? Maybe in Dockerfile or i can do it from docker-compose.yml?

我的意思是,我不知道何时何地使用CREATE DATABASE;创建表...;查询我是否使用流行数据库的Docker容器

I mean, that I dont know when and where to use CREATE DATABASE; CREATE TABLE ...; queries if I use docker containers of popular databases

您可以同时使用docker和docker-compose.例如,使用docker compose.

You can use both docker and docker-compose. For example with docker compose.

创建一个名为docker-compose.yml的文件,如下所示:

Create a file called docker-compose.yml like:

version: '3'
services:
  db:
    image: percona:5.7
    container_name: whatever_you_want
    environment:
      - MYSQL_DATABASE=${DATABASE}
      - MYSQL_ROOT_PASSWORD=${ROOT_PASSWORD}
      - MYSQL_USER=${USER}
      - MYSQL_PASSWORD=${PASSWORD}
    volumes:
      - ./data:/docker-entrypoint-initdb.d
    ports:
      - "3306:3306"

此外,您还需要./data下的文件以及要运行的任何SQL命令,并且需要.env文件,用于定义我在上述docker-compose.yml文件中使用的环境变量,例如:${DATABASE}

Additionally you need a file under ./data with whatever SQL commands you want to run and and .env file where you define the environmental variables I used in the docker-compose.yml file above like: ${DATABASE}

您的.env文件:

# MySQL
DATABASE=db_name_here
ROOT_USER=root
ROOT_PASSWORD=root
USER=dev
PASSWORD=dev

使用SQL命令执行./data/init.sql的文件(您可以根据需要命名文件)

Your file with SQL commands to execute ./data/init.sql (you can name the file whatever you want)

CREATE DATABASE 'whatever';
DROP DATABASE 'whatever';
-- you can do whatever you want here

此文件将在您每次执行时执行:

This file will be executed each time you do:

docker-compose up -d db