[英]mount mysql-db to docker-container
I have this little node-app for testing. 我有这个小节点应用程序进行测试。 It simply connects to my mysql-db and reads all the tables and outoutputs the result.
它只是连接到我的mysql-db并读取所有表并输出结果。
var http = require('http');
var mysql = require('mysql');
var server = http.createServer(function(req, res) {
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: 'earth2'
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "SHOW tables;";
con.query(sql, function (err, result) {
if (err) throw err;
console.log('HI FROM SERVER');
res.setHeader('Content-type', 'text/plain' );
res.end(JSON.stringify(result));
});
});
}).listen(3000, function () {
console.log('########### NODE SERVER START ################');
console.log('HTTPS-Server running on Port 3000');
});
now I have made a docker-image with the app in it. 现在我已经在其中创建了带有应用程序的docker-image。 this is my dockerfile:
这是我的dockerfile:
FROM djudorange/node-gulp-mocha
COPY /test .
CMD ["node", "test.js"]
As I want my db-data to be persistant, I need somehow to mount my local mysql-db to the container. 因为我希望我的db-data是持久性的,所以我需要以某种方式将本地mysql-db挂载到容器中。 but how exactly does this work?
但是这到底如何工作?
The information I find is somewhat confusing for me as a noob. 我作为新手对我发现的信息有些困惑。
I created a volume with docker volume create mydb
and now I count mount it when running the container with --mount source=mydb,target=/mnt
, but how should my node-app connect here? 我用
docker volume create mydb
创建了一个卷,现在我用--mount source=mydb,target=/mnt
运行容器时将其--mount source=mydb,target=/mnt
,但是我的node-app应该如何在这里连接?
Best approach would be to use docker-compose
. 最好的方法是使用
docker-compose
。 If you want to use docker run
, there are couple of ways. 如果要使用
docker run
,则有两种方法。 Start mysql with: 用以下命令启动mysql:
docker run -v <absolute/path/to/store/data/in/host>:/var/lib/mysql/ -p 3306:3306 mysql
which persists mysql container's datadir /var/lib/mysql/
in your <absolute/path/to/store/data/in/host>
and exposes port 3306 in host machine. 它在您的
<absolute/path/to/store/data/in/host>
中持久保存mysql容器的数据目录/var/lib/mysql/
,并在主机中公开端口3306。 Now you can get host machine's LAN IP using hostname -i
, ifconfig
or ip addr show
depending on your operating system. 现在,根据您的操作系统,可以使用
hostname -i
, ifconfig
或ip addr show
获取主机的LAN IP。 In nodejs app, replace localhost
with the host machine's IP. 在nodejs应用中,将
localhost
替换为主机的IP。
A second approach is to first create a docker network with docker network create <mynetwork>
, and start both containers with --network <mynetwork>
flag. 第二种方法是,首先使用
docker network create <mynetwork>
创建一个docker network create <mynetwork>
,然后使用--network <mynetwork>
标志启动两个容器。 If you now do docker run --name <mydb> ...
, you can reference mysqldb in your node app as mydb:3306
如果现在执行
docker run --name <mydb> ...
,则可以在节点应用程序中将mysqldb引用为mydb:3306
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.