Rafaeltab
Rafaeltab

Reputation: 171

How can I add postgresql to an existing dockerfile?

I am working on an ASP.NET Core API project with docker support. I was hoping I could add postgresql or mysql to my dockerfile and have it just work. Now, I don't have much experience with docker at all however I am happy with what it does and how it works (especially that my pc doesn't get cluttered with random programs that I don't need except for one project).

I have tried the example from https://docs.docker.com/engine/examples/postgresql_service/ However it doesn't really look like it should work to me and I like to know how my stuff works. So even if it works properly I'd rather have a solution where it looks more like this:

FROM postgresql:11.5
EXPOSE 5432
ENV <add password environment variable here>

The dockerfile I have before adding postgresql is

FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build
WORKDIR /src
COPY ["ModOs__Api/ModOs__Api.csproj", "ModOs__Api/"]
RUN dotnet restore "ModOs__Api/ModOs__Api.csproj"
COPY . .
WORKDIR "/src/ModOs__Api"
RUN dotnet build "ModOs__Api.csproj" -c Release -o /app

FROM build AS publish
RUN dotnet publish "ModOs__Api.csproj" -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .

ENTRYPOINT ["dotnet", "ModOs__Api.dll"]

When the postgres is added I'd like to simply be able to connect to it at the URL localhost:5432 in the c# code. Also, if possible it would be awesome if I can view the databases in my browser (However, if this makes things 10x more complicated please don't waste time on it).

What is the best or a great way of doing this?

Thanks in advance!

Upvotes: 1

Views: 2031

Answers (1)

vidstige
vidstige

Reputation: 13085

You don't. Although possible, I would advice against doing it like this. The philosophy with Docker is that each service runs in it's own container. If you follow this paradigm, things will be much easier for you. On the upside, there is a beaten path for this making this comfortable. Check out this simple docker compose file for example

version: '3'
services:
  web:
    build: .
    ports:
      - "80:80"
  postgres:
    image: "postgres:9.6"

Instead of connecting to localhost:5432 you connect to postgres:5432.

Spin everything up with docker-compose up

Upvotes: 2

Related Questions