Calling API in a docker-compose container to another container - nginx

I'm making an web service using docker-compose environment. But I face to the calling API issue. I'm using nextjs and here is my code.
import { GetServerSideProps } from 'next';
export default function Home() {
return (
...
);
}
export const getServerSideProps: GetServerSideProps = async ({ req }) => {
fetch('http://localhost:7070/api/users') // <-- error occurred !
.then((r) => r.json())
.then((result) => console.log('######## shoot in getServerSideProps', result));
return {
props: {},
};
};
This is sample code. When I access to this page, the following error comes up
/app/node_modules/node-fetch/lib/index.js:1461
reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
^
FetchError: request to http://localhost:7070/api/users failed, reason: connect ECONNREFUSED 127.0.0.1:7070
How can I call the fetch API?
My docker setting is following.
docker-compose
version: "3"
services:
servicebackend:
container_name: seiwhale-backend
build:
dockerfile: Dockerfile.dev
context: ./services/server
volumes:
- /app/node_modules
- ./services/server:/app
servicefrontend:
container_name: seiwhale-frontend
build:
dockerfile: Dockerfile.dev
context: ./services/webapp
volumes:
- /app/node_modules
- ./services/webapp:/app
serviceredis:
container_name: seiwhale-redis
image: "redis"
nginx:
container_name: seiwhale-nginx
restart: always
build:
dockerfile: Dockerfile
context: ./services/nginx
ports:
- "7070:80"
nginx
upstream upstreamfrontend {
server servicefrontend:8080;
}
upstream upstreambackend {
server servicebackend:3000;
}
server {
listen 80;
location / {
proxy_pass http://upstreamfrontend;
}
location /api {
proxy_pass http://upstreambackend;
}
location /sockjs-node {
proxy_pass http://upstreamfrontend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
}
}
Additionally, when the error was occurred, the frontend container is automatically exited like following
seiwhale-frontend exited with code 1
How can I re-run the frontend container after exit?

2 mistakes:
You are missing the expose key from your docker-compose.yml config in which you define a list of ports that you want to expose to other services in the same docker network (or in this case, services defined in the same docker-compose file).
The frontend code running as a docker service and not from the host, so again you need to use expose and not port. (port is used for mapping ports from HOST:CONTAINER so applications outside the docker network can call it, for example, if something is listening on port 4200 of servicebackend and you define 8000:4200 then it is accessible on your host at localhost:8000.)
Please try again after making the following changes:
docker-compose.yml
version: "3"
services:
servicebackend:
container_name: seiwhale-backend
build:
dockerfile: Dockerfile.dev
context: ./services/server
volumes:
- /app/node_modules
- ./services/server:/app
expose:
- "3000"
servicefrontend:
container_name: seiwhale-frontend
build:
dockerfile: Dockerfile.dev
context: ./services/webapp
volumes:
- /app/node_modules
- ./services/webapp:/app
expose:
- "8080"
serviceredis:
container_name: seiwhale-redis
image: "redis"
nginx:
container_name: seiwhale-nginx
restart: always
build:
dockerfile: Dockerfile
context: ./services/nginx
ports:
- "7070:80"
expose:
- "80"
and in the frontend,
export const getServerSideProps: GetServerSideProps = async ({ req }) => {
fetch('http://localhost:80/api/users') // <-- error occurred !
.then((r) => r.json())
.then((result) => console.log('######## shoot in getServerSideProps', result));
.error((err) => console.error(err))
return {
props: {},
};
};

Related

Azure Web App Service + Docker Compose + NGINX Reverse Proxy -- 502 Error in Deployment

as the title states, I have created a full stack application that uses FastAPI as the backend, and ReactJS as the frontend. I also have a third container for my Nginx reverse proxy. Reason I have this third container is so that I can make calls to my backend from the client's browser using the service/container names I create in the docker-compose.yaml file.
I then use the compose file to build and run all 3 of those containers. When I am working locally, everything works great at the localhost endpoint on my browser. However, when I try to deploy to Azure Web App Service, I am only able to load the frontend (React) home page. When I open the console, I receive an error saying 502 (Bad Gateway).
Below is a snippet of my ReactJS code that makes a post request for authentication
import React, { useEffect, useContext } from 'react';
import { Redirect, Route } from 'react-router-dom';
import Cookies from 'js-cookie';
import { AuthContext } from './contexts/AuthContext';
const PrivateRoute = ({ component: Component, ...rest }) => {
// Import the functions to set states
const { isAuthenticated, setIsAuthenticated, setUsername } =
useContext(AuthContext);
// Read in the access token; if not available, make empty string
const accessToken =
Cookies.get('access_token') == null ? '' : Cookies.get('access_token');
// Create the use effect function to generate the component
useEffect(() => {
fetch(`${window.location.protocol}//${window.location.hostname}/backend/auth/validate_token`, {
method: 'POST',
mode: 'cors',
credentials: 'include',
headers: {
Accept: 'application/json',
},
body: JSON.stringify({
token: accessToken,
}),
})
.then((response) => {
return response.json();
})
.then((response) => {
// Set the view based on the return
if (response) {
setIsAuthenticated(true);
setUsername(response.username);
} else {
setIsAuthenticated(false);
}
});
});
return (
<>
<Route
{...rest}
render={() => {
if (isAuthenticated) {
return <Component {...rest} />;
} else {
return <Redirect to='/login' />;
}
}}
/>
</>
);
};
export { PrivateRoute };
Below is my docker compose file
version: "3"
services:
reverse-proxy:
container_name: reverse-proxy
build:
context: ./proxy
dockerfile: Dockerfile
image: ilecontainerregistry.azurecr.io/proxy:latest
ports:
- 80:80
- 443:443
depends_on:
- frontend
- backend
frontend:
container_name: frontend
domainname: "usps-ile"
# Remove the build command for configuration file in azure web app service
build:
context: ./frontend
dockerfile: Dockerfile
image: ilecontainerregistry.azurecr.io/frontend:latest
ports:
- 8080:80
env_file:
- ./frontend/.env
backend:
container_name: backend
domainname: "usps-ile"
# Remove the build command for configuration file in azure web app service
build:
context: ./backend
dockerfile: Dockerfile
image: ilecontainerregistry.azurecr.io/backend:latest
ports:
- 3000:3000
env_file:
- ./backend/app/.env
Below is my dockerfile for the nginx container
FROM nginx:latest
COPY nginx.conf /etc/nginx/
And lastly, here is my nginx.conf file
events {
worker_connections 1024;
}
http {
upstream backend{
server backend:3000;
}
server {
listen 80;
listen 443;
server_name _;
location / {
proxy_pass http://frontend:80/;
}
location /backend/ {
proxy_pass http://backend/;
}
}
}
Below is a snippet from the FastAPI backend for the authentication post route in Python
#auth_router.post("auth/validate_token", tags=["Auth"])
async def validate_token(token: Token):
'''
This function is responsible for
reading in the token in an object
and validating if it is still valid
'''
try:
# Get the access token from the request cookie
authorization: str = token.token
# Split the access token on the space "Bearer" "xxxxxxxxx-token"
scheme, access_token = get_authorization_scheme_param(authorization)
# Decode the token and check if it is valid
decoded_token = jwt.decode(
token=access_token,
key=os.getenv("SECRET_KEY"),
algorithms=[os.getenv("ALGORITHM")]
)
return decoded_token
except Exception as e:
return False
Thank you in advance!
Looks like I figured out a solution that worked for me, I originally had the PORT for FastAPI exposed at 3000 (what i set it during development) but when I tried to deploy it with docker compose, I was having some issues with container communication.
I defaulted back to the normal PORT 80 for the fastapi container and changed my nginx conf file to look like the following and it worked like a charm! Hope I can help anyone else that was stuck.
events {
worker_connections 1024;
}
http {
server {
listen 80;
server_name _;
location / {
proxy_pass http://frontend:80/;
}
location /backend/ {
proxy_pass http://backend:80/;
}
}
}

Ocelot + consul + my web api (.Net 5) via HTTPS in docker

I'm trying to use Ocelot (Api gateway) + consul + my web api (.Net 5) via HTTPS in docker;
ocelot - v17.0.0
consul - latest https://hub.docker.com/_/consul
my service - ASP.NET 5 Web Api
Trust HTTPS certificate from Windows Subsystem for Linux
source: https://learn.microsoft.com/en-us/aspnet/core/security/enforcing-ssl?view=aspnetcore-5.0&tabs=visual-studio#trust-https-certificate-from-windows-subsystem-for-linux
MY_SECRET_PROJECT_PATH\LicenseServiceWebApi> dotnet dev-certs https --clean
Cleaning HTTPS development certificates from the machine. A prompt might get displayed to confirm the removal of some of the certificates.
HTTPS development certificates successfully removed from the machine.
MY_SECRET_PROJECT_PATH\LicenseServiceWebApi> dotnet dev-certs https -ep $env:USERPROFILE\.aspnet\https\aspnetdev.pfx -p <водкабалалайка>
The HTTPS developer certificate was generated successfully.
MY_SECRET_PROJECT_PATH\LicenseServiceWebApi> dotnet dev-certs https --trust
Trusting the HTTPS development certificate was requested. A confirmation prompt will be displayed if the certificate was not previously trusted. Click yes on the prompt to trust the certificate.
A valid HTTPS certificate is already present.
My docker-compose:
version: '3'
services:
license-service-web-api-01:
image: license-service-web-api
container_name: license-service-01
build:
context: .
dockerfile: Services/LicenseServiceWebApi/Dockerfile
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=https://+:9001;http://+:9000
- ASPNETCORE_Kestrel__Certificates__Default__Password=${Kestrel_Certificate_Password}
- ASPNETCORE_Kestrel__Certificates__Default__Path=/root/.aspnet/https/aspnetdev.pfx
volumes:
- ${USERPROFILE}\.aspnet\https:/root/.aspnet/https/:ro
ports:
- 9000:9000
- 9001:9001
depends_on:
- consul
gateway:
image: gateway
container_name: gateway
build:
context: .
dockerfile: ApiGateway/gateway/Dockerfile
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=https://+:5001;http://+:5000
- ASPNETCORE_Kestrel__Certificates__Default__Password=${Kestrel_Certificate_Password}
- ASPNETCORE_Kestrel__Certificates__Default__Path=/root/.aspnet/https/aspnetdev.pfx
volumes:
- ${USERPROFILE}\.aspnet\https:/root/.aspnet/https/:ro
ports:
- 5001:5001
- 5000:5000
depends_on:
- consul
consul:
image: consul
container_name: consul
command: agent -server -ui -node=server-1 -bootstrap-expect=1 -client=0.0.0.0
environment:
- 'CONSUL_LOCAL_CONFIG= {"connect": {"enabled": true}}'
ports:
- 8500:8500
My configuration file "ocelot.json" (version without Consul)
{
"Routes": [
{
"SwaggerKey": "License Service",
"DownstreamPathTemplate": "/api/{everything}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "license-service-web-api-01",
"Port": 9000
}
],
"UpstreamHttpMethod": [ "Put", "Post", "GET" ],
"UpstreamPathTemplate": "/{everything}",
"LoadBalancerOptions": {
"Type": "LeastConnection"
},
"FileCacheOption": {
"TtlSeconds": 30
}
},
{
"DownstreamPathTemplate": "/swagger/{everything}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "license-service-web-api-01",
"Port": 9000
}
],
"UpstreamPathTemplate": "/swagger/{everything}",
"FileCacheOption": {
"TtlSeconds": 666
}
}
],
"SwaggerEndPoints": [
{
"Key": "License Service",
"Config": [
{
"Name": "License Service API",
"Version": "v1",
"Service": {
"Name": "License Service",
"Path": "/swagger/v1/swagger.json"
}
}
]
}
]
}
docker-compose ps
Name Command State Ports
----------------------------------------------------------------------------------------------------------------------------------------------------------
consul docker-entrypoint.sh agent ... Up 8300/tcp, 8301/tcp, 8301/udp, 8302/tcp, 8302/udp, 0.0.0.0:8500->8500/tcp, 8600/tcp, 8600/udp
gateway dotnet gateway.dll Up 443/tcp, 0.0.0.0:5000->5000/tcp, 0.0.0.0:5001->5001/tcp
license-service-01 dotnet LicenseServiceWebAp ... Up 443/tcp, 0.0.0.0:9000->9000/tcp, 0.0.0.0:9001->9001/tcp
CASE 1:
PS C:\Users\tim> curl http://localhost:9000/api/HealthCheck/GetMachineName
StatusCode : 200
StatusDescription : OK
Content : MachineName=2a429d520129
RawContent : HTTP/1.1 200 OK
PS C:\Users\tim> curl https://localhost:9001/api/HealthCheck/GetMachineName
StatusCode : 200
StatusDescription : OK
Content : MachineName=2a429d520129
RawContent : HTTP/1.1 200 OK
PS C:\Users\tim> curl http://localhost:5000/HealthCheck/GetMachineName
StatusCode : 200
StatusDescription : OK
Content : MachineName=2a429d520129
RawContent : HTTP/1.1 200 OK
PS C:\Users\tim> curl https://localhost:5001/HealthCheck/GetMachineName
StatusCode : 200
StatusDescription : OK
Content : MachineName=2a429d520129
RawContent : HTTP/1.1 200 OK
CASE 2:
I added an https redirect in my service
app.UseHttpsRedirection();
PS C:\Users\tim> curl http://localhost:9000/api/HealthCheck/GetMachineName
StatusCode : 200
StatusDescription : OK
Content : MachineName=345437c4c182
RawContent : HTTP/1.1 200 OK
PS C:\Users\tim> curl https://localhost:9001/api/HealthCheck/GetMachineName
StatusCode : 200
StatusDescription : OK
Content : MachineName=345437c4c182
RawContent : HTTP/1.1 200 OK
PS C:\Users\tim> curl http://localhost:5000/HealthCheck/GetMachineName
curl : Unable to resolve the remote name: 'license-service-web-api-01'
docker-compose logs ..
gateway | info: Ocelot.RateLimit.Middleware.ClientRateLimitMiddleware[0]
gateway | requestId: 0HM6VQAI1UTJU:00000002, previousRequestId: no previous request id, message: EndpointRateLimiting is not enabled for /api/{everything}
gateway | info: Ocelot.Authentication.Middleware.AuthenticationMiddleware[0]
gateway | requestId: 0HM6VQAI1UTJU:00000002, previousRequestId: no previous request id, message: No authentication needed for /HealthCheck/GetMachineName
gateway | info: Ocelot.Authorization.Middleware.AuthorizationMiddleware[0]
gateway | requestId: 0HM6VQAI1UTJU:00000002, previousRequestId: no previous request id, message: /api/{everything} route does not require user to be authorized
gateway | info: Ocelot.Requester.Middleware.HttpRequesterMiddleware[0]
gateway | requestId: 0HM6VQAI1UTJU:00000002, previousRequestId: no previous request id, message: 307 (Temporary Redirect) status code, request uri: http://license-service-web-api-01:9000/api/HealthCheck/GetMachineName
PS C:\Users\tim> curl https://localhost:5001/HealthCheck/GetMachineName
curl : Unable to resolve the remote name: 'license-service-web-api-01'
..The logs are the same
CASE 3
I'm changed configuration file ocelot.json on https and port 9001
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "license-service-web-api-01",
"Port": 9001
}
],
AND
removed line app.UseHttpsRedirection(); in my service
GET https://localhost:5001/WeatherForecast
502
225 ms
Warning: Unable to verify the first certificate
GET /WeatherForecast HTTP/1.1
User-Agent: PostmanRuntime/7.26.8
Accept: */*
Postman-Token: 6cafa9e0-e195-4082-a7d4-daac4f58dff7
Host: localhost:5001
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
HTTP/1.1 502 Bad Gateway
Date: Fri, 05 Mar 2021 14:50:01 GMT
Server: Kestrel
Content-Length: 0
gateway | info: Ocelot.RateLimit.Middleware.ClientRateLimitMiddleware[0]
gateway | requestId: 0HM6VSNQ8J5GI:00000002, previousRequestId: no previous request id, message: EndpointRateLimiting is not enabled for /api/{everything}
gateway | info: Ocelot.Authentication.Middleware.AuthenticationMiddleware[0]
gateway | requestId: 0HM6VSNQ8J5GI:00000002, previousRequestId: no previous request id, message: No authentication needed for /WeatherForecast
gateway | info: Ocelot.Authorization.Middleware.AuthorizationMiddleware[0]
gateway | requestId: 0HM6VSNQ8J5GI:00000002, previousRequestId: no previous request id, message: /api/{everything} route does not require user to be authorized
gateway | warn: Ocelot.Responder.Middleware.ResponderMiddleware[0]
gateway | requestId: 0HM6VSNQ8J5GI:00000002, previousRequestId: no previous request id, message: Error Code: ConnectionToDownstreamServiceError Message: Error connecting to downstream service, exception: System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
gateway | ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch, RemoteCertificateChainErrors
gateway | at System.Net.Security.SslStream.SendAuthResetSignal(ProtocolToken message, ExceptionDispatchInfo exception)
gateway | at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm)
gateway | at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Boolean async, Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
gateway | --- End of inner exception stack trace ---
gateway | at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Boolean async, Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
gateway | at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
gateway | at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
gateway | at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
gateway | at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
gateway | at System.Net.Http.DiagnosticsHandler.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
gateway | at System.Net.Http.HttpClient.SendAsyncCore(HttpRequestMessage request, HttpCompletionOption completionOption, Boolean async, Boolean emitTelemetryStartStop, CancellationToken cancellationToken)
gateway | at Ocelot.Requester.HttpClientHttpRequester.GetResponse(HttpContext httpContext) errors found in ResponderMiddleware. Setting error response for request path:/WeatherForecast, request method: GET
I have questions, maybe someone can help me, please:
Why ocelot can't call my serive over https?
How i can https enabled for Consul inside docker - compose?
you have a ssl error last case. You may 2 options for this issue
best.option you creating your own certificate and then getting it trusted by your local or remote machine.
quick option you can add this line your ocelot.json
"DangerousAcceptAnyServerCertificateValidator": true
you should add networks tag on your docker-compose file.
like below:
version: '3'
networks:
dockerapi:
driver: bridge
services:
license-service-web-api-01:
image: license-service-web-api
container_name: license-service-01
build:
context: .
dockerfile: Services/LicenseServiceWebApi/Dockerfile
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=https://+:9001;http://+:9000
- ASPNETCORE_Kestrel__Certificates__Default__Password=${Kestrel_Certificate_Password}
- ASPNETCORE_Kestrel__Certificates__Default__Path=/root/.aspnet/https/aspnetdev.pfx
volumes:
- ${USERPROFILE}\.aspnet\https:/root/.aspnet/https/:ro
ports:
- 9000:9000
- 9001:9001
depends_on:
- consul
networks:
- dockerapi
gateway:
image: gateway
container_name: gateway
build:
context: .
dockerfile: ApiGateway/gateway/Dockerfile
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=https://+:5001;http://+:5000
- ASPNETCORE_Kestrel__Certificates__Default__Password=${Kestrel_Certificate_Password}
- ASPNETCORE_Kestrel__Certificates__Default__Path=/root/.aspnet/https/aspnetdev.pfx
volumes:
- ${USERPROFILE}\.aspnet\https:/root/.aspnet/https/:ro
ports:
- 5001:5001
- 5000:5000
depends_on:
- consul
networks:
- dockerapi

NET 5.0 web project - unable to change connection URL at startup (+ Docker)

I think I pretty much tried every possible way but no matter what I do, my NET 5.0 web app always connects to localhost:5000.
At startup I get this:
webbackend | warn: Microsoft.AspNetCore.Server.Kestrel[0]
webbackend | Unable to bind to http://localhost:5000 on the IPv6 loopback interface: 'Cannot assign requested address'.
webbackend | info: Microsoft.Hosting.Lifetime[0]
webbackend | Now listening on: http://localhost:5000
webbackend | info: Microsoft.Hosting.Lifetime[0]
webbackend | Application started. Press Ctrl+C to shut down.
webbackend | info: Microsoft.Hosting.Lifetime[0]
webbackend | Hosting environment: Production
webbackend | info: Microsoft.Hosting.Lifetime[0]
webbackend | Content root path: /app
Even though I have these in place:
Program.cs:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseKestrel()
.UseStartup<Startup>()
.UseUrls(http://0.0.0.0:80);
});
appsettings.json:
"commands": {
"web": "Microsoft.AspNet.Server.Kestrel --server.urls http://0.0.0.0:80"
}
Dockerfile:
ENTRYPOINT ["dotnet", "webbackend.dll", "--urls", "http://0.0.0.0:80"]
docker-compose.yml:
webbackend:
image: local_webbackend
container_name: webbackend
networks:
- my_network
environment:
ASPNETCORE_URLS: http://+:80
ports:
- "5001:80"
expose:
- "5432"
- "5001"
depends_on:
postgresdb:
condition: service_healthy
I really don't understand what is going on.
I just want this app to connect to localhost:80 inside its docker container. This port should then be connected to 5001 in the docker-compose network.
First you can change the UseUrls settings in Program.cs IHostBuilder
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseKestrel()
.UseStartup<Startup>()
.UseUrls("http://localhost:80/");
});
You can use the default Dockerfile created by Visual Studio or download it from Microsoft docs (you can specify all the parameters in docker-compose too, the important thing is to expose port 80, or other port that you have specified in the settings above). The settings are exposing the port 80 by default. In your docker-compose file you can set the settings like this:
webbackend:
image: local_webbackend
build: <path to generated or created Dockerfile>
container_name: webbackend
networks:
- my_network
environment:
ASPNETCORE_URLS: http://+:80
ports:
- "5001:80"
depends_on:
postgresdb:
condition: service_healthy
With this settings, apps inside the docker network, should connect to your app using URL like: webbacked:80. You can reach the app from your PC using: localhost:5001 and other devices from your LAN: :5001 (for example 192.168.1.100:5001).

Meteor Up - Error: connect ECONNREFUSED 192.168.100.12:

I have a Meteor App based on Angular 1.3 + Meteor 1.5.2.2.
I am using Ubuntu 17.
I am trying to deploy my Meteor App on local machine first before going for live server using Meteor Up.
But I am facing this issue when running mup setup command
martinihenry#martinihenry:~/mytestapp-prod/.deploy$ mup setup
Started TaskList: Setup Docker
[192.168.100.12] - Setup Docker
events.js:141
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 192.168.100.12:22
at Object.exports._errnoException (util.js:907:11)
at exports._exceptionWithHostPort (util.js:930:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1078:14)
Here is my mup.json:
module.exports = {
servers: {
one: {
// TODO: set host address, username, and authentication method
host: '192.168.100.12',
username: 'root',
// pem: './path/to/pem'
// password: 'server-password'
// or neither for authenticate from ssh-agent
}
},
app: {
// TODO: change app name and path
name: 'mytestapp-prod',
path: '../',
servers: {
one: {},
},
buildOptions: {
serverOnly: true,
},
env: {
// TODO: Change to your app's url
// If you are using ssl, it needs to start with https://
ROOT_URL: '192.168.100.12:3000',
MONGO_URL: 'mongodb://localhost/meteor',
},
// ssl: { // (optional)
// // Enables let's encrypt (optional)
// autogenerate: {
// email: 'email.address#domain.com',
// // comma separated list of domains
// domains: 'website.com,www.website.com'
// }
// },
docker: {
// change to 'kadirahq/meteord' if your app is using Meteor 1.3 or older
image: 'abernix/meteord:base',
},
// Show progress bar while uploading bundle to server
// You might need to disable it on CI servers
enableUploadProgressBar: true
},
mongo: {
version: '3.4.1',
servers: {
one: {}
}
}
};
What could be wrong here?
It looks like you don't have sshd running on your machine, or you have not enabled remote ssh access for root.
You need to edit /etc/ssh/sshd_config, and comment out the following line:
PermitRootLogin without-password
Just below it, add the following line:
PermitRootLogin yes
Then restart SSH:
service ssh restart
I know this is late, but this a known and reproducable bug resulting from inotfiy-watch using all of the available slots for watches, and while very misleading, it actually has absolutely nothing to do with disk space.
The easy fix? increase watch slots:
sudo -i
echo 1048576 > /proc/sys/fs/inotify/max_user_watches
exit

How to read environment variable In ASP.NET core 2.0 +Docker?

I have ASP.NET core 2.0 webAPI and using Mysql database.So I am configuring the "ConnectionString" in application.json file. When I am running it locally, I am able to read the connection string and application is working perfect. But it is not when I try to deploy to docker using Docker toolbox. I have written three files :-
Dockerfile
DockerCompose
Proxy.Conf
I am using docker compose file because I have to run on ngnix server. I am able to build to image and as well as to run it. Now I am trying to overwrite the connection string from docker-compose file but Its is not getting overwrite.
DockerFile
FROM microsoft/aspnetcore:2.0
ARG source
WORKDIR /app
COPY $source .
EXPOSE 5000
ENTRYPOINT ["dotnet", "xx.dll"]
docker-compose.yaml
version: '2'
services:
app:
container_name: cp-api
build: .
environment:
- "ConnectionStrings:Test=server=192.168.99.101; port=3306; user=root; password=X123; database=TestDb; TreatTinyAsBoolean=true;"
rev-proxy:
container_name: rev-proxy
image: nginx
ports:
- "9090:8080"
volumes:
- ./proxy.conf:/etc/nginx/conf.d/default.conf`
Proxy.conf
server {
listen 8080;
location / {
proxy_pass http://cp-api:5000;
}
}
appsetting.json:-
{
"ConnectionStrings": {
"EcallDbNextGen": "server =192.168.99.100; port =3306; user =root; password =xxx; database =Testdb; TreatTinyAsBoolean=true;"
},
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
}
}
Startup.cs
public Startup(IConfiguration configuration, ILoggerFactory loggerFactory) {
Configuration = configuration;
loggerFactory.AddConsole(Configuration.GetSection("Logging")); //log levels set in your configuration
loggerFactory.AddDebug(); //does all log levels
//removed rest of code
}
public IConfiguration Configuration {
get;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) {
var connection = Configuration.GetConnectionString("EcallDbNextGen");
services.AddDbContext < ecallnextgendbContext > (options => options.UseMySql(connection));
}

Resources