简体   繁体   中英

How to dockerize aspnet core application and postgres sql with docker compose

In the process of integrating the docker file into my previous sample project so everything was automated for easy code sharing and execution. I have some dockerize problem and tried to solve it but to no avail. Hope someone can help. Thank you. Here is my problem:

My repository: https://github.com/ThanhDeveloper/WebApplicationAspNetCoreTemplate

Branch for dockerize (my problem in macOS): https://github.com/ThanhDeveloper/WebApplicationAspNetCoreTemplate/pull/1

Docker file:

# syntax=docker/dockerfile:1
FROM node:16.11.1
FROM mcr.microsoft.com/dotnet/sdk:5.0
RUN apt-get update && \
    apt-get install -y wget && \
    apt-get install -y gnupg2 && \
    wget -qO- https://deb.nodesource.com/setup_6.x | bash - && \
    apt-get install -y build-essential nodejs
COPY . /app
WORKDIR /app
RUN ["dotnet", "restore"]
RUN ["dotnet", "build"]
RUN dotnet tool restore
EXPOSE 80/tcp
RUN chmod +x ./entrypoint.sh
CMD /bin/bash ./entrypoint.sh

Docker compose:

version: "3.9"
services:
    web:
        container_name: backendnet5
        build: .
        ports:
            - "5005:5000"
        depends_on:
            - database
    database:
        container_name: postgres
        image: postgres:latest
        ports: 
            - "5433:5433"
        environment:
            - POSTGRES_PASSWORD=admin
        volumes:
            - ./init.sql:/docker-entrypoint-initdb.d/init.sql

Commands:

docker-compose build
docker compose up

Problems: 在此处输入图像描述

在此处输入图像描述

I guess the problem is not being able to run command line dotnet ef database update my migrations. Many thanks for any help.

In your appsettings.json file, you say that the database hostname is 'localhost'. In a container, localhost means the container itself.

Docker compose creates a bridge network where you can address each container by it's service name.

You connection string is

User ID=postgres;Password=admin;Host=localhost;Port=5432;Database=sample_db;Pooling=true;

but should be

User ID=postgres;Password=admin;Host=database;Port=5432;Database=sample_db;Pooling=true;

You also map port 5433 on the database to the host, but postgres listens on port 5432. If you want to map it to port 5433 on the host, the mapping in the docker compose file should be 5433:5432 . This is not what's causing your issue though. This just prevents you from connecting to the database from the host, if you need to do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM