C
C#10mo ago
Ares

✅ [ASP.NET CORE] Error when trying to run docker image i pushed to dockerhub

so i built, tagged, then uploaded my asp.net project to docker hub, and then i downloaded the compose.yaml, Dockerfile, and .dockerignore, and .csproj from my repo: . so i have all those 4 files in a empty folder called Docker. And then I pull my image from docker hub and then i use docker compose up to run the image using the yaml file. It starts building but then stops suddenly, complaining about a Main class in program.cs (but Im not even writing a console app?)
63 Replies
Ares
AresOP10mo ago
D:\docker>docker compose up
[+] Building 3.9s (12/14) docker:default
=> [server internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 2.67kB 0.0s
=> [server] resolve image config for docker.io/docker/dockerfile:1 0.2s
=> CACHED [server] docker-image://docker.io/docker/dockerfile:1@sha256:ac85f380a63b13dfcefa89046420e1781752bab20 0.0s
=> [server internal] load metadata for mcr.microsoft.com/dotnet/aspnet:8.0-alpine 0.1s
=> [server internal] load metadata for mcr.microsoft.com/dotnet/sdk:8.0-alpine 0.1s
=> [server internal] load .dockerignore 0.0s
=> => transferring context: 643B 0.0s
=> [server internal] load build context 0.0s
=> => transferring context: 5.21kB 0.0s
=> [server final 1/3] FROM mcr.microsoft.com/dotnet/aspnet:8.0-alpine@sha256:95f27052830db1c7a00e55f098ebda50720 0.0s
=> [server build 1/4] FROM mcr.microsoft.com/dotnet/sdk:8.0-alpine@sha256:e646d8a0fa589bcd970e0ebde394780398e8ae 0.0s
=> CACHED [server build 2/4] COPY . /source 0.0s
=> CACHED [server build 3/4] WORKDIR /source 0.0s
=> ERROR [server build 4/4] RUN --mount=type=cache,id=nuget,target=/root/.nuget/packages dotnet publish -a $ 3.3s
------
D:\docker>docker compose up
[+] Building 3.9s (12/14) docker:default
=> [server internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 2.67kB 0.0s
=> [server] resolve image config for docker.io/docker/dockerfile:1 0.2s
=> CACHED [server] docker-image://docker.io/docker/dockerfile:1@sha256:ac85f380a63b13dfcefa89046420e1781752bab20 0.0s
=> [server internal] load metadata for mcr.microsoft.com/dotnet/aspnet:8.0-alpine 0.1s
=> [server internal] load metadata for mcr.microsoft.com/dotnet/sdk:8.0-alpine 0.1s
=> [server internal] load .dockerignore 0.0s
=> => transferring context: 643B 0.0s
=> [server internal] load build context 0.0s
=> => transferring context: 5.21kB 0.0s
=> [server final 1/3] FROM mcr.microsoft.com/dotnet/aspnet:8.0-alpine@sha256:95f27052830db1c7a00e55f098ebda50720 0.0s
=> [server build 1/4] FROM mcr.microsoft.com/dotnet/sdk:8.0-alpine@sha256:e646d8a0fa589bcd970e0ebde394780398e8ae 0.0s
=> CACHED [server build 2/4] COPY . /source 0.0s
=> CACHED [server build 3/4] WORKDIR /source 0.0s
=> ERROR [server build 4/4] RUN --mount=type=cache,id=nuget,target=/root/.nuget/packages dotnet publish -a $ 3.3s
------
> [server build 4/4] RUN --mount=type=cache,id=nuget,target=/root/.nuget/packages dotnet publish -a ${TARGETARCH/amd64/x64} --use-current-runtime --self-contained false -o /app:
0.702 MSBuild version 17.9.4+90725d08d for .NET
0.862 Determining projects to restore...
1.779 Restored /source/realTimePolls.csproj (in 641 ms).
3.236 CSC : error CS5001: Program does not contain a static 'Main' method suitable for an entry point [/source/realTimePolls.csproj]
------
failed to solve: process "/bin/sh -c dotnet publish -a ${TARGETARCH/amd64/x64} --use-current-runtime --self-contained false -o /app" did not complete successfully: exit code: 1
> [server build 4/4] RUN --mount=type=cache,id=nuget,target=/root/.nuget/packages dotnet publish -a ${TARGETARCH/amd64/x64} --use-current-runtime --self-contained false -o /app:
0.702 MSBuild version 17.9.4+90725d08d for .NET
0.862 Determining projects to restore...
1.779 Restored /source/realTimePolls.csproj (in 641 ms).
3.236 CSC : error CS5001: Program does not contain a static 'Main' method suitable for an entry point [/source/realTimePolls.csproj]
------
failed to solve: process "/bin/sh -c dotnet publish -a ${TARGETARCH/amd64/x64} --use-current-runtime --self-contained false -o /app" did not complete successfully: exit code: 1
Ares
AresOP10mo ago
No description
Ares
AresOP10mo ago
i tried goign to project properties and changing the output to Class Library instead of Console Application and then i rebuilt and reuploaded the image but that didnt work
Keswiik
Keswiik10mo ago
Console Application is the correct type for an asp.net core project.
Ares
AresOP10mo ago
ok, i guess thats how it is then. but i dont understand why its looking for a Main method if i have no Main.cs. it must be looking in program.cs, i dont understand why its looking for a main method if line 89 is causing the issue, i commented it out and rebuilt and it still is not working
Lecco
Lecco10mo ago
all program begins with Main function but in your code there is node Main function
Ares
AresOP10mo ago
i dont think i understand, where is the Main function then? i thought the entry point for asp.net apps was startup.cs or program.cs
Keswiik
Keswiik10mo ago
top level statements are valid in recent c# versions. First thing you should do is update your dockerfile with some commands that list what directory it is in and what files are present when you start your build My guess is something is being copied to the wrong directory Or you're using an outdated base image that does not support top-level statements
Lecco
Lecco10mo ago
I think if you add static Main method in your code you can fix error like: public partial class Program { public static void Main(string[] args) { // Entry point of the program } }
Ares
AresOP10mo ago
ok i saw that online but didnt try it cause felt kind of like a bandaid fix but i will try
Lecco
Lecco10mo ago
okay.then let me know.
Ares
AresOP10mo ago
ok
6.182 CSC : error CS5001: Program does not contain a static 'Main' method suitable for an entry point [/source/realTimePolls.csproj]
------
failed to solve: process "/bin/sh -c dotnet publish -a ${TARGETARCH/amd64/x64} --use-current-runtime --self-contained false -o /app" did not complete successfully: exit code: 1
6.182 CSC : error CS5001: Program does not contain a static 'Main' method suitable for an entry point [/source/realTimePolls.csproj]
------
failed to solve: process "/bin/sh -c dotnet publish -a ${TARGETARCH/amd64/x64} --use-current-runtime --self-contained false -o /app" did not complete successfully: exit code: 1
still doeesnt work unfortunately i dont know why
./Program.cs
...stufff
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"
);
});

app.MapHub<PollHub>("/pollHub");

app.Run();

public partial class Program
{
public static void Main(string[] args)
{
// Entry point of the program
}
}
./Program.cs
...stufff
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"
);
});

app.MapHub<PollHub>("/pollHub");

app.Run();

public partial class Program
{
public static void Main(string[] args)
{
// Entry point of the program
}
}
i added it here
Lecco
Lecco10mo ago
or try it :all of your code rewrite in Main method
Ares
AresOP10mo ago
ok one sec
public partial class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);

..stuff
}
}
public partial class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);

..stuff
}
}
still no luck, i wrapped everything in the program function but i stil get the same error
Keswiik
Keswiik10mo ago
You should probably take my advice and make sure your files are being properly copied into your docker container.
Lecco
Lecco10mo ago
me too.
Ares
AresOP10mo ago
ok one sec
Lecco
Lecco10mo ago
how is about?
Ares
AresOP10mo ago
i dont know to be honest it works fine locally when i run it from inside my project, but when i pull from my dockerhub and run it with just my yaml, dockerfile, .dockerignore, postgres.env , and my .sln it doesnt work. maybe i am missing a file or something cause when i run the same docker compose up in my project i have no errors
RUN --mount=type=cache,id=nuget,target=/root/.nuget/packages \
dotnet publish -a ${TARGETARCH/amd64/x64} --use-current-runtime --self-contained false -o /app
RUN --mount=type=cache,id=nuget,target=/root/.nuget/packages \
dotnet publish -a ${TARGETARCH/amd64/x64} --use-current-runtime --self-contained false -o /app
i think there is something wrong with this part of Dockerfile because it is where the docker compose up fails but im not sure whats wrong with it
Keswiik
Keswiik10mo ago
What compose file are you using when you pull the image from the docker registry? Because that command is part of your container build process and should not be executed by anyone trying to use the image normally.
Ares
AresOP10mo ago
i am using the same compose file as the one that was used to build the docker image:
# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Docker compose reference guide at
# https://docs.docker.com/go/compose-spec-reference/

# Here the instructions define your application as a service called "server".
# This service is built from the Dockerfile in the current directory.
# You can add other services your application may depend on here, such as a
# database or a cache. For examples, see the Awesome Compose repository:
services:
server:
build:
context: .
target: final
ports:
- 8080:8080
# The commented out section below is an example of how to define a PostgreSQL
# database that your application can use. `depends_on` tells Docker Compose to
# start the database before your application. The `db-data` volume persists the
# database data between container restarts. The `db-password` secret is used
# to set the database password. You must create `db/password.txt` and add
# a password of your choosing to it before running `docker compose up`.
environment:
- ASPNETCORE_ENVIRONMENT=Development
- IS_DOCKER=true
depends_on:
db:
condition: service_healthy
develop:
watch:
- action: rebuild
path: .
db:
image: postgres
restart: always
user: postgres
secrets:
- db-password
volumes:
- db-data:/var/lib/postgresql/data
- ./init-db.sql:/docker-entrypoint-initdb.d/init-db.sql
environment:
- POSTGRES_DB=realtime_poll
env_file:
- ./postgres.env

expose:
- 5432
healthcheck:
test: [ "CMD", "pg_isready" ]
interval: 10s
timeout: 5s
retries: 5
volumes:
db-data:
secrets:
db-password:
file: db/password.txt
# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Docker compose reference guide at
# https://docs.docker.com/go/compose-spec-reference/

# Here the instructions define your application as a service called "server".
# This service is built from the Dockerfile in the current directory.
# You can add other services your application may depend on here, such as a
# database or a cache. For examples, see the Awesome Compose repository:
services:
server:
build:
context: .
target: final
ports:
- 8080:8080
# The commented out section below is an example of how to define a PostgreSQL
# database that your application can use. `depends_on` tells Docker Compose to
# start the database before your application. The `db-data` volume persists the
# database data between container restarts. The `db-password` secret is used
# to set the database password. You must create `db/password.txt` and add
# a password of your choosing to it before running `docker compose up`.
environment:
- ASPNETCORE_ENVIRONMENT=Development
- IS_DOCKER=true
depends_on:
db:
condition: service_healthy
develop:
watch:
- action: rebuild
path: .
db:
image: postgres
restart: always
user: postgres
secrets:
- db-password
volumes:
- db-data:/var/lib/postgresql/data
- ./init-db.sql:/docker-entrypoint-initdb.d/init-db.sql
environment:
- POSTGRES_DB=realtime_poll
env_file:
- ./postgres.env

expose:
- 5432
healthcheck:
test: [ "CMD", "pg_isready" ]
interval: 10s
timeout: 5s
retries: 5
volumes:
db-data:
secrets:
db-password:
file: db/password.txt
so when i pull it i use this compose.yaml too to do docker compose up. but i should not be doing this?
Keswiik
Keswiik10mo ago
No, you shouldn't. Remove the build section of your compose file and try again. Its attempting to build the container and none of the files it needs are there.
Ares
AresOP10mo ago
ok
Ares
AresOP10mo ago
its not running anymore when i remove the build section
No description
Ares
AresOP10mo ago
Microsoft Windows [Version 10.0.19045.4046]
(c) Microsoft Corporation. All rights reserved.

D:\docker>docker compose up
service "server" has neither an image nor a build context specified: invalid compose project

D:\docker>docker compose up
validating D:\docker\compose.yaml: services.server.build must be a string

D:\docker>
Microsoft Windows [Version 10.0.19045.4046]
(c) Microsoft Corporation. All rights reserved.

D:\docker>docker compose up
service "server" has neither an image nor a build context specified: invalid compose project

D:\docker>docker compose up
validating D:\docker\compose.yaml: services.server.build must be a string

D:\docker>
//compose.yaml
services:
server:
build:
#removed build
ports:
- 8080:8080
//compose.yaml
services:
server:
build:
#removed build
ports:
- 8080:8080
Pobiega
Pobiega10mo ago
You didn't remove the section header Also, if pulling all the images from hub you should only need the compose file, nothing else Certainly not the csproj or dockerfile or SLN
Ares
AresOP10mo ago
ok
Pobiega
Pobiega10mo ago
Your compose is clearly written for development, you'll want a second compose for running the pre-built image
Ares
AresOP10mo ago
ok
services:
server:
ports:
- 8080:8080
environment:
- ASPNETCORE_ENVIRONMENT=Development
- IS_DOCKER=true
depends_on:
db:
condition: service_healthy
develop:
watch:
- action: rebuild
path: .
db:
image: postgres
restart: always
user: postgres
secrets:
- db-password
volumes:
- db-data:/var/lib/postgresql/data
- ./init-db.sql:/docker-entrypoint-initdb.d/init-db.sql
environment:
- POSTGRES_DB=realtime_poll
env_file:
- ./postgres.env

expose:
- 5432
healthcheck:
test: [ "CMD", "pg_isready" ]
interval: 10s
timeout: 5s
retries: 5
volumes:
db-data:
secrets:
db-password:
file: db/password.txt
services:
server:
ports:
- 8080:8080
environment:
- ASPNETCORE_ENVIRONMENT=Development
- IS_DOCKER=true
depends_on:
db:
condition: service_healthy
develop:
watch:
- action: rebuild
path: .
db:
image: postgres
restart: always
user: postgres
secrets:
- db-password
volumes:
- db-data:/var/lib/postgresql/data
- ./init-db.sql:/docker-entrypoint-initdb.d/init-db.sql
environment:
- POSTGRES_DB=realtime_poll
env_file:
- ./postgres.env

expose:
- 5432
healthcheck:
test: [ "CMD", "pg_isready" ]
interval: 10s
timeout: 5s
retries: 5
volumes:
db-data:
secrets:
db-password:
file: db/password.txt
i removed the section header and then when in a seperate directory where i just have a differnetcompose.yaml, whenever i do docker compose up it says:
D:\docker>docker compose up
2024/02/29 01:04:19 http2: server: error reading preface from client //./pipe/docker_engine: file has already been closed
[+] Building 0.5s (5/5) FINISHED docker:default
=> [server internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 2.66kB 0.0s
=> [server] resolve image config for docker.io/docker/dockerfile:1 0.3s
=> CACHED [server] docker-image://docker.io/docker/dockerfile:1@sha256:ac85f380a63b13dfcefa89046420e1781752bab20 0.0s
=> ERROR [server internal] load metadata for mcr.microsoft.com/dotnet/sdk:8-alpine 0.1s
=> CANCELED [server internal] load metadata for mcr.microsoft.com/dotnet/aspnet:8-alpine 0.1s
------
> [server internal] load metadata for mcr.microsoft.com/dotnet/sdk:8-alpine:
------
failed to solve: mcr.microsoft.com/dotnet/sdk:8-alpine: mcr.microsoft.com/dotnet/sdk:8-alpine: not found
D:\docker>docker compose up
2024/02/29 01:04:19 http2: server: error reading preface from client //./pipe/docker_engine: file has already been closed
[+] Building 0.5s (5/5) FINISHED docker:default
=> [server internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 2.66kB 0.0s
=> [server] resolve image config for docker.io/docker/dockerfile:1 0.3s
=> CACHED [server] docker-image://docker.io/docker/dockerfile:1@sha256:ac85f380a63b13dfcefa89046420e1781752bab20 0.0s
=> ERROR [server internal] load metadata for mcr.microsoft.com/dotnet/sdk:8-alpine 0.1s
=> CANCELED [server internal] load metadata for mcr.microsoft.com/dotnet/aspnet:8-alpine 0.1s
------
> [server internal] load metadata for mcr.microsoft.com/dotnet/sdk:8-alpine:
------
failed to solve: mcr.microsoft.com/dotnet/sdk:8-alpine: mcr.microsoft.com/dotnet/sdk:8-alpine: not found
my other yaml is like this
services:
server:
build:
context: .
target: final
ports:
- 8080:8080
depends_on:
db:
condition: service_healthy
db:
image: postgres
restart: always
user: postgres
secrets:
- db-password
volumes:
- db-data:/var/lib/postgresql/data
environment:
- POSTGRES_DB=example
- POSTGRES_PASSWORD_FILE=/run/secrets/db-password
expose:
- 5432
healthcheck:
test: [ "CMD", "pg_isready" ]
interval: 10s
timeout: 5s
retries: 5
volumes:
db-data:
secrets:
db-password:
file: db/password.txt
services:
server:
build:
context: .
target: final
ports:
- 8080:8080
depends_on:
db:
condition: service_healthy
db:
image: postgres
restart: always
user: postgres
secrets:
- db-password
volumes:
- db-data:/var/lib/postgresql/data
environment:
- POSTGRES_DB=example
- POSTGRES_PASSWORD_FILE=/run/secrets/db-password
expose:
- 5432
healthcheck:
test: [ "CMD", "pg_isready" ]
interval: 10s
timeout: 5s
retries: 5
volumes:
db-data:
secrets:
db-password:
file: db/password.txt
Pobiega
Pobiega10mo ago
And there is the build directive again You should have one compose file that builds and runs the image from source for development, and a separate one for running only images pulled from the hub This second file should not contain any build or develop directives It should however contain image/tag names so it can pull the image from the hub
Ares
AresOP10mo ago
ok, but i already pulled the image from the hub by myself, does it still need image/tag names to do that?
Pobiega
Pobiega10mo ago
The compose file shouldn't be ambiguous, or make assumptions Tags are optional, if you want to use latest But you will need the image name I don't mean to be rude but it seems you don't really understand docker very well
Ares
AresOP10mo ago
no not really i mean i think buildign and pushing to hub is okay but i dont know how to use it
Pobiega
Pobiega10mo ago
Ok so heres my "super quick guide to docker" ™... a Dockerfile is for building an image. Its only really used with docker build and produces an image as a result. When running a prebuilt image, you use either docker run or a compose file (if you have multiple images that depend on eachother) In a "prod-like" as in production-like environment, you should only be running pre-built images and assume nothing is available locally thats special. Look at the compose file you pasted, at the db section. Thats what a normal, "prod-like" section looks like you should have one like that for your image too, since its treated exactly the same so remove the build and developsections, add image and restart and you're good to go You will need nothing except the "prod-like" compose file when running your app this way all the other stuff, like Dockerfile, .dockerignore, csproj, sln, are part of your development
Ares
AresOP10mo ago
but there are things like enviornment variables, like database passwords. i dont think taht can be apart of the image that you build? unless you hard code it but you shouldnt do that right?
Pobiega
Pobiega10mo ago
correct, those should be specified in the compose file too, if needed anything you want the user/host of the program to be able to change must be controlled via an env-var
Ares
AresOP10mo ago
so that means the user would have to have their own .env file? thats what i was doing with the postgres.env before
Pobiega
Pobiega10mo ago
.env isnt a normal format in C# world
Ares
AresOP10mo ago
ok
Pobiega
Pobiega10mo ago
so it depends on how you use it a more standard approach would be to have the user add their environment variables to the compose file, like postgres does and in DEVELOPMENT you might use an .env file but in "prod" mode, you read it all via the environment variables on the system, provided by the compose file
Ares
AresOP10mo ago
but that doesnt make any sense because, if it is reading all the environment variables from the system, it wont have a database password for example, so that means they would have to add it to the yaml themselves?
Pobiega
Pobiega10mo ago
yes your app doesnt know how the postgres is configured it also doesnt know if the user wants to run postgres in docker, or on a separate machine, etc you shouldnt care about that. just say "my app requires postgres, feed it a valid connection string via environment variables" and thats it. the rest is up to the user but you can, as a nice person, provide a compose.yaml that does this already
Ares
AresOP10mo ago
volumes:
db-data:
secrets:
db-password:
file: db/password.txt
volumes:
db-data:
secrets:
db-password:
file: db/password.txt
but for this part for example you are supposed to put your database password in a new folder called db in a text file called password.txt. isnt this something that the user has to do? or no? that means it shouldnt be in the prod compose.yaml right``
Pobiega
Pobiega10mo ago
I've never seen that way of doing it before you can have a password exposed in that file just fine btw
Ares
AresOP10mo ago
but what if you dont want them to connect to the prod database, you want them to use their own local database
Pobiega
Pobiega10mo ago
they cant connect to your database anyways lol compose.yaml is local to the place running it if I do docker compose up and you do too, with the same file, we both have two identical local environments dockerhub doesnt run any images, it just hosts the actual image files
Ares
AresOP10mo ago
ok i still am very confused to be honest i dont even know what questions to ask like it was working fine locally and then i hosted it i thought i was using it right but then when i remembered that the purpose of docker is so you dont have to clone the repo then here i just got completely lost
Pobiega
Pobiega10mo ago
the purpose of docker is to fix "works on my machine" "bugs" all images should be self-contained ready to run images, with configuration done via environment variables and/or loading a volume with config files on it, for very complicated apps
Ares
AresOP10mo ago
i was able to build my image and it works when i ran it but then when i pulled it and pretended to be a stranger trying to use it then i got all sorts of errors and wasnt able to use it at all. so i thouight maybe the compose.yaml i amde for development was bad. but then i thought that maybe the app itself was bad and not using it properly so now i am deceiding on what exactly i need to do im not sure
Pobiega
Pobiega10mo ago
you might have over-configured your app in appsettings.json or .env so you might need to pull some of those settings out to env vars for the compose file to be able to set them properly depends a bit on how you set up your configuration
Ares
AresOP10mo ago
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"GoogleKeys": {
"ClientId": "",
"ClientSecret": ""
},
"ConnectionStrings": {
"DockerConnection": "Host=db;Port=5432;Database=realtime_poll;User Id=postgres;Password="",
"DevelopmentConnection": "Host=localhost;Port=5432;Database=realtime_poll;User Id=postgres;Password="",
"DefaultConnection": "Host=dpg-cndt50v109ks738t6lt0-a.ohio-postgres.render.com;Port=5432;Database=realtimepoll_server;User Id=realtimepoll_server_user;Password=""
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"GoogleKeys": {
"ClientId": "",
"ClientSecret": ""
},
"ConnectionStrings": {
"DockerConnection": "Host=db;Port=5432;Database=realtime_poll;User Id=postgres;Password="",
"DevelopmentConnection": "Host=localhost;Port=5432;Database=realtime_poll;User Id=postgres;Password="",
"DefaultConnection": "Host=dpg-cndt50v109ks738t6lt0-a.ohio-postgres.render.com;Port=5432;Database=realtimepoll_server;User Id=realtimepoll_server_user;Password=""
}
}
i read that i shouldnt be using appsetigns.json like this so i think maybe this is where i went wrong
Pobiega
Pobiega10mo ago
yesn't. You should let the user set the connectionstring - with docker this means via an environment variable you could set a default docker connstr that assumes the user hasnt touched the shipped with compose file however in ASP.NET default configuration, environment variables can override the settings set in appsettings.json for local development stuff, use appsettings.Development.json or dotnet user-secrets
Ares
AresOP10mo ago
ok im just getting a bit overwhelemed now cause i have alot to focus on now like for example in my Program.cs:
builder.Services.AddDbContext<RealTimePollsContext>(options =>
{
var connectionString = string.Empty;

if (Environment.GetEnvironmentVariable("IS_DOCKER") == "true")
connectionString = builder.Configuration.GetConnectionString("DockerConnection");
else if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Production")
connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
else
connectionString = builder.Configuration.GetConnectionString("DevelopmentConnection");

options.UseNpgsql(connectionString);
});
builder.Services.AddDbContext<RealTimePollsContext>(options =>
{
var connectionString = string.Empty;

if (Environment.GetEnvironmentVariable("IS_DOCKER") == "true")
connectionString = builder.Configuration.GetConnectionString("DockerConnection");
else if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Production")
connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
else
connectionString = builder.Configuration.GetConnectionString("DevelopmentConnection");

options.UseNpgsql(connectionString);
});
i am conditionaly setting the connection string and thats why i have IS_DOCKER= true as an environment variable in compose.yaml but this is also bad to do too right?
Pobiega
Pobiega10mo ago
yep options.UseNpgsql(builder.Configuration.GetConnectionString("DatabaseConnection")); is all you need then you set that configuration value via envvars to the three different connstrs you want user secrets for local dev, compose file can set the other one, and default to the default one in appsettings.json not really sure why you have 3 btw
Ares
AresOP10mo ago
i had three because for some reason whenever i would try to get the baseURL in the view javascript it wouldnt work if i had https for some reason it only works with http and I had no idea why so i did this but i think this is also bad too right?:
const baseURL = environment === "Production" ? "https://realtime-poll.onrender.com/" : location.port === "8080" ?
`http://localhost:${location.port}/` : `https://localhost:${location.port}/`;
const baseURL = environment === "Production" ? "https://realtime-poll.onrender.com/" : location.port === "8080" ?
`http://localhost:${location.port}/` : `https://localhost:${location.port}/`;
Pobiega
Pobiega10mo ago
if you distribute via docker, why would you need a "production but not docker" setup anyways, just let the user set the connstr themself but have a reasonable default thats what I'd do ie, default to it working with the default postgres docker setup :p
Ares
AresOP10mo ago
when you say to let the user set it by themselves: you mean they should go to the compose.yaml that I give them, and manually enter it under environment?
environment:
- ASPNETCORE_ENVIRONMENT=Development
- IS_DOCKER=true
environment:
- ASPNETCORE_ENVIRONMENT=Development
- IS_DOCKER=true
Pobiega
Pobiega10mo ago
yeah, if they want to change it you could also split it up into separate vars for database name/user/password/host and re-build the connstr inside your app that means the user can change only the password, etc but your app is a webapp with a webserver - its not unreasonable to expect the user to have basic knowledge to use it
Ares
AresOP10mo ago
ok i have alot of new information now but i am just kidn of overhwlemened now do you think i should start with fixing all of the appsettings.json and just having one string there? and the user can set it in the compose.yaml? and then after that i can remove all of the conditional stuff in the Program.cs like you showed before? would that be the first thing i should do?
Pobiega
Pobiega10mo ago
suuure? I have seen only the snippets you've shown, but .. yeah? I'd read up on how dotnet does configuration if I were you https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-8.0 https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-8.0 learning how to set up your configs for multiple environments is important
Ares
AresOP10mo ago
ok i think i will just start with reading the docs and then try to fix my project from there cause the way id id it doesnt reall make sense now that i think about it so thanks
Pobiega
Pobiega10mo ago
np. this stuff can be pretty complicated at first, so dont sweat it you need to get it wrong a few times before you get it right 🙂
Ares
AresOP10mo ago
ok thanks
Want results from more Discord servers?
Add your server