我想提取docker postgres映像并在其中创建数据库mydb
。我可以这样一步一步地完成
docker run -d -p 5432:5432 --name containername -e POSTGRES_PASSWORD=password -d postgres:12.1
docker exec -it containername /bin/bash
psql -h localhost -U postgres
CREATE database mydb;
我想在自述文件中添加这些步骤。运行容器本身时,是否可以用单个命令完成所有操作? 尝试过类似下面的操作,但无法成功
docker run -d -p 5432:5432 --name terminals -e POSTGRES_PASSWORD=password -d postgres:12.1 psql -h localhost -U postgres; create database terminals
答案 0 :(得分:0)
您可以将初始化脚本装入容器:
docker run -d -v /local-path/your-init.sql:/docker-entrypoint-initdb.d/your-init.sql -p 5432:5432 --name containername -e POSTGRES_PASSWORD=password postgres:12.1
your-init.sql:
CREATE database mydb;
答案 1 :(得分:0)
Postgres官方docker映像(例如您当前正在使用的postgres:12.1)带有docker-entrypoint.sh脚本,该脚本能够基于env变量(documentation来初始化数据库,@ Zeitounator也提到过) 。 因此,为了启动postgres并在启动时启动数据库,您需要在运行映像时添加一个额外的env变量(POSTGRES_DB = mydb):
const { Op } = Sequelize;
const { organizations } = req.body;
try {
// get all Organization matches for the IDs
const organizationsArray = await Organization.findAll({
attributes: ['id'], // we only need the ID
where: {
id: {
[Op.in]: organizations, // WHERE id IN (organizations)
}
},
raw: true, // no need to create Instances
});
// create an array of the IDs we found
const foundIds = organizationsArray.map((org) => org.id);
// check to see if any of the IDs are missing from the results
if (foundIds.length !== organizations.length) {
// Use Array.reduce() to figure out which IDs are missing from the results
const missingIds = organizations.reduce((missingIds, orgId) => {
if (!foundIds.includes(orgId)){
missingIds.push(orgId);
}
return missingIds;
}, []); // initialized to empty array
throw new Error(`Unable to find Organization for: ${missingIds.join(', ')}`);
}
// now create an array of courses to create using the foundIds
const courses = foundIds.map((orgId) => {
return {
course_id: id,
organization_id: orgId,
};
});
// if we get here there were no errors, create the records
await CoursesOrganizations.bulkCreate(courses);
// return a success to the client
return res.json({ success: true });
} catch (err) {
// there was an error, return it to the client
return res.status(400).json({ error: err.message });
}