gpt4 book ai didi

docker - 使用docker保留数据库中的数据

转载 作者:行者123 更新时间:2023-12-02 18:32:55 24 4
gpt4 key购买 nike

我已经创建了database.sql文件并将其添加到容器内的文件夹中,以便应用程序可以使用它。我希望即使删除容器后我的数据也应保持持久性。我尝试使用volume.But如何添加。 sql文件,并使该文件一致。

sudo docker -v /datadir sqldb 

在这里,sqldb是数据库镜像名称,而datadir是安装文件夹。

sqldb的Dockerfile:
FROM ubuntu:latest

RUN apt-get update
RUN apt-get upgrade -y

RUN apt-get -y install mysql-client mysql-server curl
ADD ./my.cnf /etc/mysql/my.cnf

RUN sed -i -e"s/^bind-address\s*=\s*127.0.0.1/bind-address = 0.0.0.0/" /etc/mysql/my.cnf

ADD database.sql /var/db/database.sql

ENV user root
ENV password password
ENV url file:/var/db/database.sql
ENV right WRITE

ADD ./start-database.sh /usr/local/bin/start-database.sh
RUN chmod +x /usr/local/bin/start-database.sh
EXPOSE 3306

CMD ["/usr/local/bin/start-database.sh"]

start-database.sh文件
#!/bin/bash

# This script starts the database server.
echo "Creating user $user for databases loaded from $url"
a
# Import database if provided via 'docker run --env url="http:/ex.org/db.sql"'
echo "Adding data into MySQL"
/usr/sbin/mysqld &
sleep 5
curl $url -o import.sql

# Fixing some phpmysqladmin export problems
sed -ri.bak 's/-- Database: (.*?)/CREATE DATABASE \1;\nUSE \1;/g' import.sql

# Fixing some mysqldump export problems (when run without --databases switch)
# This is not tested so far
# if grep -q "CREATE DATABASE" import.sql; then :; else sed -ri.bak 's/-- MySQL dump/CREATE DATABASE `database_1`;\nUSE `database_1`;\n-- MySQL dump/g' import.sql; fi

mysql --default-character-set=utf8 < import.sql
rm import.sql
mysqladmin shutdown
echo "finished"

# Now the provided user credentials are added
/usr/sbin/mysqld &
sleep 5
echo "Creating user"
echo "CREATE USER '$user' IDENTIFIED BY '$password'" | mysql --default-character-set=utf8
echo "REVOKE ALL PRIVILEGES ON *.* FROM '$user'@'%'; FLUSH PRIVILEGES" | mysql --default-character-set=utf8
echo "GRANT SELECT ON *.* TO '$user'@'%'; FLUSH PRIVILEGES" | mysql --default-character-set=utf8
echo "finished"

if [ "$right" = "WRITE" ]; then
echo "adding write access"
echo "GRANT ALL PRIVILEGES ON *.* TO '$user'@'%' WITH GRANT OPTION; FLUSH PRIVILEGES" | mysql --default-character-set=utf8
fi

# And we restart the server to go operational
mysqladmin shutdown
cp /var/db/database.sql /var/lib/docker/volumes/mysqlvol/database.sql
echo "Starting MySQL Server"
/usr/sbin/mysqld

最佳答案

为了即使在卸下容器后也能保持数据持久性,请使用卷。
有关更多信息,请参见:

  • SO: How to deal with persistent storage (e.g. databases) in docker
  • Docker Webinar Q&A: Persistent Storage & Docker
  • Manage data in containers
  • Compose and volumes
  • Volume plugins

  • 希望对您有所帮助。如果没有,请询​​问。

    关于docker - 使用docker保留数据库中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34309961/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com