【发布时间】:2021-06-06 11:21:56
【问题描述】:
所以我有一个不和谐,但我目前在家里的服务器上运行它。我现在决定从头开始设置服务器。现在我在服务器上有 MySQL 和程序(不是在 docker 容器中),我现在想 Dockerize 它。
为了简单起见,我决定只扩展 MySQL 容器,但我一直遇到错误。现在一切正常,只是程序没有连接到 MySQL 服务器。
我尝试使用
启动应用程序CMD ./PokeBot
结果是连接被拒绝错误。首先,我尝试公开端口 3306 并使用127.0.0.1 作为 MySQL 服务器的 IP。没有任何效果。
然后我发现 MySQL 服务器没有运行,所以我创建了一个 Bash Shell 脚本 (.sh) 来启动 MySQL 服务器,但随后我收到了错误 Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root!。
如何在 Docker 容器中与 MySQL 一起运行程序?
我启动容器的命令:
docker run -p 3306:3306 name
项目结构:
这是我的 Dockerfile:
FROM mysql:latest as builder
# That file does the DB initialization but also runs mysql daemon, by removing the last line it will only init
RUN ["sed", "-i", "s/exec \"$@\"/echo \"not running $@\"/", "/usr/local/bin/docker-entrypoint.sh"]
# needed for intialization
ENV MYSQL_ROOT_PASSWORD=asdfghjkl
COPY setup.sql /docker-entrypoint-initdb.d/
ADD ca-certificates.crt /etc/ssl/certs/
# Need to change the datadir to something else that /var/lib/mysql because the parent docker file defines it as a volume.
# https://docs.docker.com/engine/reference/builder/#volume :
# Changing the volume from within the Dockerfile: If any build steps change the data within the volume after
# it has been declared, those changes will be discarded.
RUN ["/usr/local/bin/docker-entrypoint.sh", "mysqld", "--datadir", "/initialized-db"]
FROM mysql:latest
ENV MYSQL_ROOT_PASSWORD=asdfghjkl
ADD ca-certificates.crt /etc/ssl/certs/
COPY PokeBot /
COPY --from=builder /initialized-db /var/lib/mysql
COPY start.sh /
EXPOSE 3306
RUN apt update
RUN apt install ca-certificates sudo -y
RUN update-ca-certificates
CMD ./start.sh
这是我的 DDL 脚本(之后会填充数据):
CREATE DATABASE pokebot;
USE pokebot;
CREATE USER 'pokebot'@'%' IDENTIFIED WITH mysql_native_password BY 'asdfghjkl';
GRANT ALL PRIVILEGES ON pokebot.* TO 'pokebot'@'%';
FLUSH PRIVILEGES;
CREATE TABLE image(
id INT NOT NULL AUTO_INCREMENT,
srclink VARCHAR(255) NOT NULL,
imglink VARCHAR(255) NOT NULL,
text VARCHAR(255) NOT NULL,
command VARCHAR(16) NOT NULL,
CONSTRAINT pk PRIMARY KEY (id)
);
我的setup.sh:
sudo mysqld &
./PokeBot
Go 中失败的部分:
db, err := sql.Open("mysql", "pokebot:asdfghjkl@tcp(127.0.0.1:3306)/pokebot")
if err != nil {
log.Print(err.Error())
}
【问题讨论】:
-
您几乎总是将它们作为两个单独的容器运行。类似于官方的 Docker Django and PostgreSQL 示例应用程序是一种不同的实现语言和数据库,但仍然展示了如何一起运行单独的数据库和应用程序容器。