I created 2 Application:
API Project
GRPC service Project
In the api project, I access GRPC services, when I run application on IIS Server then it's working fine but when I hosted those application on my local machine in docker Container then it's not working.
This is my Docker file of API project
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["wc.account.api/wc.account.api.csproj", "wc.account.api/"]
COPY ["wc.signalr/wc.signalr.csproj", "wc.signalr/"]
COPY ["wc.memory.cache/wc.memory.cache.csproj", "wc.memory.cache/"]
COPY ["wc.models/wc.models.csproj", "wc.models/"]
RUN dotnet restore "wc.account.api/wc.account.api.csproj"
COPY . .
WORKDIR "/src/wc.account.api"
RUN dotnet build "wc.account.api.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "wc.account.api.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "wc.account.api.dll"]
This is Docker file of my GRPC project
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["wc.account/wc.account.csproj", "wc.account/"]
COPY ["wc.logger/wc.logger.csproj", "wc.logger/"]
COPY ["wc.models/wc.models.csproj", "wc.models/"]
RUN dotnet restore "wc.account/wc.account.csproj"
COPY . .
WORKDIR "/src/wc.account"
RUN dotnet build "wc.account.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "wc.account.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "wc.account.dll"]
this is my docker-compose.yml file
version: '3.4'
services:
wc.account.api:
image: ${DOCKER_REGISTRY-}wcaccountapi
build:
context: .
dockerfile: wc.account.api/Dockerfile
wc.account:
image: ${DOCKER_REGISTRY-}wcaccount
build:
context: .
dockerfile: wc.account/Dockerfile
I'm getting this error:
Status(StatusCode="Unavailable", Detail="Error starting gRPC call. HttpRequestException: Cannot assign requested address (localhost:49153) SocketException: Cannot assign requested address", DebugException="System.Net.Http.HttpRequestException: Cannot assign requested address (localhost:49153)
---> System.Net.Sockets.SocketException (99): Cannot assign requested address
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
at System.Net.Sockets.Socket.<ConnectAsync>g__WaitForConnectWithCancellation|277_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.AddHttp2ConnectionAsync(HttpRequestMessage request)
at System.Threading.Tasks.TaskCompletionSourceWithCancellation`1.WaitWithCancellationAsync(CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.GetHttp2ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.DiagnosticsHandler.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at Grpc.Net.Client.Internal.GrpcCall`2.GetResponseHeadersCoreAsync()")
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"grpcUrl": {
"accountUrl": "https://localhost:7163/"
},
"Authentication": {
"Key": "jaN8yp&bsffsL5Qnn6L7qyp&bsff8v3uyp&bsffsL5Qnn6L7",
"Issuer": "https://localhost:46641/",
"Audiance": "https://localhost:46641/",
"AccessExpireMinutes": "40320"
}
}
this is my AppSetting file where i Use GRPC Services
I guess you need to change your compose file.
changes like.
version: '3.4'
network:
account_network:
external: true
driver: bridge
services:
wcaccountapi:
container_name:wcaccountapi
hostname:wcaccountapi
image: ${DOCKER_REGISTRY-}wcaccountapi
build:
context: .
dockerfile: wc.account.api/Dockerfile
wcaccount:
container_name:wcaccount
hostname:wcaccount
image: ${DOCKER_REGISTRY-}wcaccount
build:
context: .
dockerfile: wc.account/Dockerfile
please check your docker file if it is wrong please update it.
next, you need to check your appsettings.json file
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"grpcUrl": {
"accountUrl": "https://wcaccount/"
},
"Authentication": {
"Key": "jaN8yp&bsffsL5Qnn6L7qyp&bsff8v3uyp&bsffsL5Qnn6L7",
"Issuer": "https://localhost:46641/",
"Audiance": "https://localhost:46641/",
"AccessExpireMinutes": "40320"
}
}
Thanks in Advance :)
Related
I have deployed a DotNet Core application on Heroku but I m receiving the following error when I'm trying to open the application
fail: ShopApi.Program[0]
An error occurred while migrating the database.
Npgsql.PostgresException (0x80004005): 28000: no pg_hba.conf entry for host "3.249.151.147", user "ddojar225ki3s4", database "ddojar225ki3s4", SSL off
at Npgsql.NpgsqlConnector.<ReadMessage>g__ReadMessageLong|194_0(NpgsqlConnector connector, Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage)
at Npgsql.NpgsqlConnector.Authenticate(String username, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlConnection.<>c__DisplayClass41_0.<<Open>g__OpenAsync|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Npgsql.NpgsqlConnection.Open()
at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists()
at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate(DatabaseFacade databaseFacade)
at ShopApi.Extensions.MigrateDatabaseExtension.MigrateDatabase[T](IHost webHost) in /src/ShopApi/Extensions/MigrateDatabaseExtension.cs:line 22
Exception data:
Severity: FATAL
SqlState: 28000
MessageText: no pg_hba.conf entry for host "3.249.151.147", user "ddojar225ki3s4", database "ddojar225ki3s4", SSL off
File: auth.c
Line: 496
Routine: ClientAuthentication
I have added an Add-On for Postgresql.
I am connecting to the database like this :
services.AddDbContext<DataContext>(optionsBuilder =>
optionsBuilder.UseNpgsql(Configuration.GetConnectionString("PostgresSqlDatabaseConnection")));
My Connection String
"PostgresSqlDatabaseConnection": "User ID=ddojar225ki3s4;Password=correct_password;Server=ec2-34-242-89-204.eu-west-1.compute.amazonaws.com;Port=5432;Database=ddojar225ki3s4;Integrated Security=true; Pooling=true"
Solution
I had to add
SSL Mode=Require; to the connection string.
Be careful NOT to type Required or SSL Mode=SSL.Require
I have 2 package.json scripts that look like this:
"start": "next start -p $PORT",
"pm2_staging": "pm2 restart ecosystem.config.js --env staging",
And an ecosystem.config.js that looks like this:
module.exports = {
apps: [
{
name: 'test.co.uk',
script: 'npm',
args: 'start',
env_staging: {
API: 'staging',
NODE_ENV: 'production',
PORT: 3001,
},
},
],
};
I then run the following:
TEST_VAR='test' npm run pm2_staging
I would expect the following to happen:
The PM2 restart command fires
ecosystem.config.js fires the npm start command and sets some environment variables
The app starts and all env vars are available, including TEST_VAR (set in the original command)
What actually happens is all the env vars from the ecosystem are correctly set, but TEST_VAR is not available in the app. Why is this and how do I go about setting secret keys from CI tools if I can't do this?
I ran into the same problem tonight. After looking every where I found the config needed. The env variable needs to go in your ecosystem.config.js like below. In my case I put it at the root of my server
module.exports = {
apps : [{
name: 'nextjs',
script: 'yarn',
args:"start",
cwd:"/var/www/myapp/",
instances: 2,
autorestart: true,
watch: false,
max_memory_restart: '1G',
env: {
NODE_ENV: 'development'
},
env_production: {
NODE_ENV: 'production',
API_URL: 'YOUR ENV URL',
PORT:8000
}
}]
};
package.json like so
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start -p 8000"
},
...
and executed something like this
#!/bin/bash
cd /var/www/myapp/
git pull && yarn install && yarn build
cd ~/
pm2 start ecosystem.config.js --env production
Then the API_URL would be available in const API_URL = process.env.API_URL in your app.
These urls helped
https://willandskill.se/en/setup-a-next-js-project-with-pm2-nginx-and-yarn-on-ubuntu-18-04/
https://pm2.keymetrics.io/docs/usage/application-declaration/
Another idea would be passing all the env parameters of PM2 to the server via the following.
ecosystem.config.js being:
module.exports = {
apps: [{
name: "my-service-1",
script: "dist/server.js",
env_production: process.env, // pass all the env params of the container to node
}],
};
#webface
The environment variables in your example will not be available in Nextjs. To be available to both the client and server, variables must be prefixed with NEXT_PUBLIC (ie. NEXT_PUBLIC_API_VERSION).
These environment variables must be passed into the build process to be available at runtime.
I'm trying to configure new pipeline in Jenkins. I have purchased and installed jFrog artifactory pro on Windows Server and it's up and running at: https://artifactory.mycompany.com
I found this sample here:
https://github.com/jfrog/project-examples/blob/master/jenkins-examples/pipeline-examples/declarative-examples/docker-push-example/Jenkinsfile
More specifically this section:
stage ('Push image to Artifactory') {
steps {
rtDockerPush(
serverId: "ARTIFACTORY_SERVER",
image: ARTIFACTORY_DOCKER_REGISTRY + '/hello-world:latest',
// Host:
// On OSX: "tcp://127.0.0.1:1234"
// On Linux can be omitted or null
host: HOST_NAME,
targetRepo: 'docker-local',
// Attach custom properties to the published artifacts:
properties: 'project-name=docker1;status=stable'
)
}
}
It's building and creating docker image but when it gets to push image it fails to push the image and errors out. Not sure what should go in the following:
ARTIFACTORY_DOCKER_REGISTRY
host: HOST_NAME
I've created a new local repo in artifactory "docker-local". Tried omitting host and getting
"Unsupported OS".
Putting host back in with "host: 'tcp://IP ADDRESSS" or "artifactory.mycompany.com:80/artifactory" generates
"Unsupported protocol scheme"
How would one configure jenkins pipeline to work with jFrog artifactory?
Found the solution:
ARTIFACTORY_DOCKER_REGISTRY should be IP/Artifactory-Repo-Key/Image:Tag
HOST should be docker daemon (Docker for windows is localhost:2375)
stage('Build image') { // build and tag docker image
steps {
echo 'Starting to build docker image'
script {
def dockerfile = 'Dockerfile'
def customImage = docker.build('10.20.111.23:8081/docker-virtual/hello-world:latest', "-f ${dockerfile} .")
}
}
}
stage ('Push image to Artifactory') { // take that image and push to artifactory
steps {
rtDockerPush(
serverId: "jFrog-ar1",
image: "10.20.111.23:8081/docker-virtual/hello-world:latest",
host: 'tcp://localhost:2375',
targetRepo: 'local-repo', // where to copy to (from docker-virtual)
// Attach custom properties to the published artifacts:
properties: 'project-name=docker1;status=stable'
)
}
}
We have an application that one can run either locally or on a remote server. When run locally, one needs to set proxies as the app uses another service on the cloud.
This is done like that:
commandLine "java", "-Xmx227m",
"-Dapplication.name=showcase-rest",
"-Dserver.port=$applicationPort",
"-Dspring.profiles.active=$springActiveProfiles",
"-Didm.realm=develop",
"-Dhttp.proxyHost=10.xx.xxx.129", "-Dhttp.proxyPort=3xxx",
"-Dhttps.proxyHost=10.xx.xxx.129", "-Dhttps.proxyPort=3xxx",
"-Dhttp.nonProxyHosts=localhost|127.0.0.1",
"-jar", tasks.jar.destinationDir.toString() + "/showcase-rest-SNAPSHOT.jar"
However, when run on proper server on the cloud, we don't need the proxy settings:
commandLine "java", "-Xmx227m",
"-Dapplication.name=showcase-rest",
"-Dserver.port=$applicationPort",
"-Dspring.profiles.active=$springActiveProfiles",
"-Didm.realm=develop",
"-jar", tasks.jar.destinationDir.toString() + "/showcase-rest-SNAPSHOT.jar"
How that could be achieved?
I know how to provide and parse jvm arguments to gradle; the question is how can I "inject" these proxy settings in the commandLine dynamically.
So far I tried:
def proxyConfig = ["-Dhttp.proxyHost=10.xx.xxx.129", "-Dhttp.proxyPort=3xxx",
"-Dhttps.proxyHost=10.xx.xxx.129", "-Dhttps.proxyPort=3xxx",
"-Dhttp.nonProxyHosts=localhost|127.0.0.1"] as List<String>
commandLine "java", "-Xmx227m",
"-Dapplication.name=showcase-rest",
"-Dserver.port=$applicationPort",
"-Dspring.profiles.active=$springActiveProfiles",
"-Didm.realm=develop",
proxyConfig,
"-jar", tasks.jar.destinationDir.toString() + "/showcase-rest-SNAPSHOT.jar"
But obviously that doesn't work.
Try this :
def params = ["java", "-Xmx227m",
"-Dapplication.name=showcase-rest",
"-Dserver.port=$applicationPort",
"-Dspring.profiles.active=$springActiveProfiles",
"-Didm.realm=develop",
"-Dhttp.proxyHost=10.xx.xxx.129", "-Dhttp.proxyPort=3xxx",
"-Dhttps.proxyHost=10.xx.xxx.129", "-Dhttps.proxyPort=3xxx",
"-Dhttp.nonProxyHosts=localhost|127.0.0.1",
"-jar", tasks.jar.destinationDir.toString() + "/showcase-rest-SNAPSHOT.jar"]
def withProxy = true
commandLine (*(params.findAll { withProxy || !it.toLowerCase().contains('proxy') }))
Thank you ToYonos. My solution, not as groovy-ninja, is below:
def proxyConfig = ["-Dhttp.proxyHost=10.xx.xxx.129",
"-Dhttp.proxyPort=3xxx",
"-Dhttps.proxyHost=10.xx.xxx.129",
"-Dhttps.proxyPort=3xxx",
"-Dhttp.nonProxyHosts=localhost|127.0.0.1"]
if (springActiveProfiles == 'cicd') {
proxyConfig = []
}
println("proxy config: $proxyConfig")
def args = ["java", "-Xmx227m",
"-Dapplication.name=showcase-rest",
"-Dserver.port=$applicationPort",
"-Dspring.profiles.active=$springActiveProfiles",
"-Didm.realm=develop"]
def jarArg = ["-jar", tasks.jar.destinationDir.toString() + "/showcase-rest-SNAPSHOT.jar"]
args.addAll(proxyConfig)
args.addAll(jarArg)
println("Running with arguments: $args")
commandLine args
I've created a .net core 2.0 project and configured it to run over HTTPS, however I cannot get Visual Studio to launch the browser with the correct scheme/port when running in Docker debug mode.
The current behaviour is VS always launches on port 80 (HTTP), and I therefore have to manually change the url each time, which is cumbersome.
Program.cs
public class Program {
public static void Main (string[] args) {
BuildWebHost(args).Run ();
}
public static IWebHost BuildWebHost (string[] args) =>
WebHost.CreateDefaultBuilder (args)
.UseKestrel (options => {
options.Listen (IPAddress.Any, GetPort(), listenOptions => {
// todo: Change this for production
listenOptions.UseHttps ("dev-cert.pfx", "idsrv3test");
});
})
.UseStartup<Startup> ()
.Build ();
public static int GetPort() => int.Parse(Environment.GetEnvironmentVariable("Port") ?? "443");
}
Dockerfile
FROM microsoft/aspnetcore:2.0
ARG source
WORKDIR /app
EXPOSE 443
COPY ${source:-obj/Docker/publish} .
ENTRYPOINT ["dotnet", "MyApp.dll"]
docker-compose.override.yml
version: '3'
services:
myapp:
environment:
- ASPNETCORE_ENVIRONMENT=Development
- Port=443
ports:
- 443
networks:
default:
external:
name: nat
Okay I have found out how to solve this myself.
Right-click the docker-compose project and go to properties.
There you can configure the Service URL that gets launched on run.
For anyone looking for code solution, what causing random port is this line in docker-compose.override.yml:
ports:
- "80"
Just remove it and add your port, for example:
ports:
- "8080:80"