问题
When I build the container of the project with this command:
sudo docker build -t PROJECT_NAME .
And then I download the mysql's image through this Docker-Compose config:
db:
image: mysql
restart: always
ports:
- "8999:3306"
networks:
- webnet
environment:
MYSQL_DATABASE: slack
MYSQL_ROOT_PASSWORD: admin
And then, the project will connect with MySQL through the Sequelize ORM
I have this error:
Unhandled rejection SequelizeConnectionRefusedError: connect ECONNREFUSED 172.18.0.4:3306
How can I resolve this?
The Sequelize config is this:
const sequelize = new Sequelize(process.env.TEST_DB || 'slack', 'root', 'admin', {
host: process.env.DB_HOST || 'localhost',
operatorsAliases: Sequelize.Op,
dialect: 'mysql',
define: {
underscored: true
}
});
The config of the web is this:
web:
image: slack-clone-server
ports:
- "8080:8080"
networks:
- webnet
environment:
DB_HOST: db
REDIS_HOST: redis
command: ["./wait-for-it.sh", "db:3306", "--", "npm", "run", "prod"]
The script called "wait for it" is this.
If someone needs the complete code, here you go:
Sequelize config
Docker Compose config
Dockerfile config
回答1:
wait-for-it.sh by default waits for 15 seconds and returns, even if the target isn't ready yet. You see that in your output too. But the database isn't ready yet. Make wait-for-it.sh wait longer, maybe with -t 90 to wait for 90 seconds or -t 0 to make it wait forever.
(In my experience the Docker database containers routinely take 30-60 seconds to start up, especially the first time.)
回答2:
David already said that the db is not ready at this moment. You can use depends_on in your docker-compose file as well. This will start and initialize the db first and then start the "web" container.
services:
web:
...
depends_on:
- db
db:
image: mariadb:latest
...
回答3:
db:
container_name: mysqldb //or whatever you want <<Add This
image: mysql
restart: always
ports:
- "8999:3306"
networks:
- webnet
environment:
MYSQL_DATABASE: slack
MYSQL_ROOT_PASSWORD: admin
And Then assign the value of process.env.DB_HOST to Mysql Container name
Like: process.env.DB_HOST=mysqldb
来源:https://stackoverflow.com/questions/51462200/docker-compose-connect-econnrefused-172-18-0-43306