Der MySQL-Server kann nicht im Docker-Container gestartet werden
P粉021854777
P粉021854777 2024-04-01 00:00:35
0
1
2497

Ich habe eine NestJS-Anwendung, die ich andocken möchte. Ich bin neu bei Docker und muss das tun. In meiner NestJS-Anwendung verwende ich eine MySQL-Datenbank mit Typeorm. Dieses MySQL selbst stammt aus dem Docker-Image, d. h. MySQL ist nicht auf meinem Computer installiert.

Ich habe diese docker-compose.yml-Datei:

# docker-compose.yml

version: '3.3'
services:
  mysql:
    image: mysql:latest
    restart: always
    environment:
      - MYSQL_USER=myuser
      - MYSQL_PASSWORD=mypassword
      - MYSQL_DATABASE=db
      - MYSQL_ROOT_USER=myuser
      - MYSQL_ROOT_PASSWORD=root

    volumes:
      - mysql:/var/lib/mysql
    ports:
      - '3306:3306'

volumes:
  mysql:

Ich kann docker-compose up -d ausführen und die Datenbank auf meinem Computer verwenden. Im Moment habe ich auch ein Dockerfle, das ich zu schreiben versuche.

Ich habe in den letzten ca. 5 Stunden einiges verändert, aber zusammenfassend sieht es so aus:

FROM ubuntu:18.04

# Set the working directory to  /usr/src/app
WORKDIR  /usr/src/app

# Copy the package.json and package-lock.json files into the container
COPY package*.json ./

RUN apt-get update
RUN apt-get -y install curl
RUN curl -sL https://deb.nodesource.com/setup_16.x | bash
RUN apt install -y nodejs

# Install the app dependencies
RUN npm install

# Copy the rest of the app files into the container
COPY . .

# Set environment variables for the MySQL connection
ENV MYSQL_HOST=mysql
ENV MYSQL_USER=myuser
ENV MYSQL_PASSWORD=mypassword
ENV MYSQL_DATABASE=db

# Install the MySQL server
RUN apt-get update -qq && apt-get install -y mysql-server

# Expose the app's port
EXPOSE 3000

# Start the app in development mode
CMD ["npm", "run", "start:dev"]

Was ich in der Doceker-Datei oben versuche, ist, ein Ubuntu-Image auf dem Host-Rechner zu erstellen und Curl, Node bzw. MySQL zu installieren, damit die Anwendung mit MySQL verwendet werden kann. Ich kann dieses Image über docker build -t my-app erstellen.

Dann habe ich Image Docker Run My-App ausgeführt und die folgende Fehlermeldung erhalten:

[Nest] 29  - 04/02/2023, 7:37:26 PM   ERROR [TypeOrmModule] Unable to connect to the database. Retrying (1)...
Error: connect ECONNREFUSED 127.0.0.1:3306
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16)

Ich weiß nicht, wie ich mit diesem Problem umgehen soll.

Als Referenz finden Sie hier meine app.module.ts-Datei

import { Module, OnModuleInit } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersModule } from './users/users.module';
import { ArtworksModule } from './artworks/artworks.module';
import { User } from './users/entities/user.entity';
import { Artwork } from './artworks/entities/artwork.entity';
import { AuthModule } from './auth/auth.module';
import { ConfigModule } from '@nestjs/config';
import { SeedService } from './users/seedService/seedService';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'myuser',
      password: 'mypassword',
      database: 'db',
      entities: [User, Artwork],
      synchronize: false,
      autoLoadEntities: true,
      logging: true,
    }),
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    UsersModule,
    ArtworksModule,
    AuthModule,
  ],
  controllers: [AppController],
  providers: [AppService, SeedService],
})
export class AppModule implements OnModuleInit {
  constructor(private seedService: SeedService) {}

  async onModuleInit() {
    await this.seedService.seedUsers();
  }
}

Was ist mit diesem Fehler los? Wie kann ich dieses Problem lösen? Vielen Dank für all die Hilfe.

Prost

BEARBEITEN: Jetzt glaube ich, dass ich das Problem etwas besser verstehe, also versuche ich, eine Docker-Compose-YML-Datei zu schreiben, die sowohl meine NestJS-App als auch mein MySQL-Image startet. Zuerst habe ich die Docker-Datei in =>

geändert
# Use the official Node.js 14 image as the base image
FROM node:14

# Create a working directory for the app
WORKDIR /app

# Copy the package.json and package-lock.json files into the container
COPY package*.json ./

# Install app dependencies
RUN npm install

# Copy the rest of the app code into the container
COPY . .

# Expose port 3000 (the port that the app listens on)
EXPOSE 3000

# Specify the command to run when the container starts
CMD [ "npm", "run", "start:prod" ]

Dann habe ich diese docker-compose.yml-Datei geschrieben =>

services:
  app:
    build: .
    command: npm run start:prod
    restart: always
    ports:
      - '3000:3000'
    environment:
      - DB_HOST=mysql
      - DB_PORT=3306
      - DB_USER=myuser
      - DB_PASSWORD=mypassword
      - DB_NAME=db
    depends_on:
      - mysql

  mysql:
    image: mysql:latest
    restart: always
    environment:
      - MYSQL_USER=myuser
      - MYSQL_PASSWORD=mypassword
      - MYSQL_DATABASE=db
      - MYSQL_ROOT_USER=myuser
      - MYSQL_ROOT_PASSWORD=root
    volumes:
      - mysql:/var/lib/mysql

volumes:
  mysql:

networks:
  default:
    driver: bridge

Wenn ich jetzt sudo docker-compose up auf Bash ausführe (ohne sudo gibt es den Fehler „Berechtigung verweigert“), erhalte ich die folgende Fehlermeldung

my-app-1    | [Nest] 19  - 04/03/2023, 8:28:03 AM   ERROR [TypeOrmModule] Unable to connect to the database. Retrying (1)...
my-app-1    | Error: connect ECONNREFUSED 127.0.0.1:3306
my-app-1    |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1159:16)
my-app-1    | [Nest] 19  - 04/03/2023, 8:28:06 AM   ERROR [TypeOrmModule] Unable to connect to the database. Retrying (2)...
my-app-1    | Error: connect ECONNREFUSED 127.0.0.1:3306
my-app-1    |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1159:16)

Soweit ich weiß, kann keine Verbindung zur Datenbank hergestellt werden. Was habe ich falsch gemacht? Wie kann ich dieses Problem lösen?

Edit 2: Basierend auf den Kommentaren habe ich einige weitere Änderungen vorgenommen. Das sind meine Erkenntnisse:

Der DB_HOST-Wert scheint keine Rolle zu spielen.

# docker-compose.yml

version: '3.3'
services:
  mysql:
    image: mysql:latest
    restart: always
    environment:
      - DB_HOST=localhost
      - MYSQL_ROOT_USER=myuser
      - MYSQL_ROOT_PASSWORD=root

    volumes:
      - mysql:/var/lib/mysql
    ports:
      - '3306:3306'

volumes:
  mysql:

Ich kann diesen Wert beliebig ändern und das Skript wird auf meinem lokalen Computer ausgeführt.

Das ist wieder meine app.module.ts-Datei =>

import { Module, OnModuleInit } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersModule } from './users/users.module';
import { ArtworksModule } from './artworks/artworks.module';
import { User } from './users/entities/user.entity';
import { Artwork } from './artworks/entities/artwork.entity';
import { AuthModule } from './auth/auth.module';
import { ConfigModule } from '@nestjs/config';
import { SeedService } from './users/seedService/seedService';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: process.env.DB_HOST,
      port: 3306,
      username: 'myuser',
      password: 'mypassword',
      database: 'db',
      entities: [User, Artwork],
      synchronize: false,
      autoLoadEntities: true,
      logging: true,
    }),
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    UsersModule,
    ArtworksModule,
    AuthModule,
  ],
  controllers: [AppController],
  providers: [AppService, SeedService],
})
export class AppModule implements OnModuleInit {
  constructor(private seedService: SeedService) {}

  async onModuleInit() {
    await this.seedService.seedUsers();
  }
}

Wenn ich versuche, diese Anwendung zu dockerisieren, damit sie auf einem Computer ausgeführt werden kann, auf dem nur Docker installiert ist, versuche ich, die Datei „docker-compose.yml“ wie =>

zu ändern
version: '3.8'

services:
  app:
    build: .
    command: npm run start:prod
    restart: always
    ports:
      - '3000:3000'
    environment:
      - DB_HOST=localhost
      - DB_PORT=3306

    depends_on:
      - mysql

  mysql:
    image: mysql:latest
    restart: always
    environment:
      - MYSQL_ROOT_USER=myuser
      - MYSQL_ROOT_PASSWORD=root

    volumes:
      - mysql:/var/lib/mysql
    ports:
      - '3306:3306'

volumes:
  mysql:

networks:
  default:
    driver: bridge

Dies führt zu zwei unterschiedlichen Verhaltensweisen: Ich kann docker-compose up nicht mehr ausführen, es wird der folgende Fehler angezeigt =>

=> [internal] load build definition from Dockerfile                                                           0.0s
 => => transferring dockerfile: 32B                                                                            0.0s
 => [internal] load .dockerignore                                                                              0.0s
 => => transferring context: 34B                                                                               0.0s
 => [internal] load metadata for docker.io/library/node:14                                                     1.4s
 => [1/5] FROM docker.io/library/node:14@sha256:a97048059988c65f974b37dfe25a44327069a0f4f81133624871de0063b98  0.0s
 => ERROR [internal] load build context                                                                        0.1s
 => => transferring context: 402.84kB                                                                          0.0s
------
 > [internal] load build context:
------
failed to solve: error from sender: open /home/sirius/coding/my-app/mysql/#innodb_redo: permission denied

Ich verwende das Fish-Terminal, also muss ich aus irgendeinem Grund zu Bash wechseln, um sudo docker-compose up auszuführen, was wiederum die folgende Fehlermeldung ausgibt, die auf ein Problem beim Herstellen der Verbindung zur Datenbank hinweist=>

e dependencies initialized +0ms
budapest-icf-recruitment-backend-app-1    | [Nest] 19  - 04/03/2023, 9:26:34 AM   ERROR [TypeOrmModule] Unable to connect to the database. Retrying (1)...
budapest-icf-recruitment-backend-app-1    | Error: connect ECONNREFUSED 127.0.0.1:3306
budapest-icf-recruitment-backend-app-1    |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1159:16)
budapest-icf-recruitment-backend-app-1    | [Nest] 19  - 04/03/2023, 9:26:37 AM   ERROR [TypeOrmModule] Unable to connect to the database. Retrying (2)...
budapest-icf-recruitment-backend-app-1    | Error: connect ECONN

Ich stecke wirklich fest.

P粉021854777
P粉021854777

Antworte allen(1)
P粉541796322

通过更改 docker-compose.yml 文件解决了所有问题,如下所示 =>

version: '3.8'

services:
  app:
    image: my-app
    build: .
    volumes:
      - .:/app
    command: npm run start:dev
    restart: always
    ports:
      - '3000:3000'
    environment:
      - DB_HOST=mysql
      - DB_PORT=3306

    depends_on:
      - mysql

  mysql:
    image: mysql:latest
    restart: always
    environment:
      - MYSQL_ROOT_USER=myuser
      - MYSQL_ROOT_PASSWORD=root

    volumes:
      - mysql:/var/lib/mysql
    ports:
      - '3306:3306'

volumes:
  mysql:

networks:
  default:
    driver: bridge

这是我的 Dockerfile =>

# Use the official Node.js 14 image as the base image
FROM node:14

# Create a working directory for the app
WORKDIR /app

# Copy the package.json and package-lock.json files into the container
COPY package*.json ./

# Install app dependencies
RUN npm install

# Copy the rest of the app code into the container
COPY . .

# Expose port 3000 (the port that the app listens on)
EXPOSE 3000

# Specify the command to run when the container starts
CMD [ "npm", "run", "start:dev" ]
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!