First of all, give thanks for reading my question and try to help me and apologize for my English.
I'm trying to run a docker with a express server project and mongo, but build Dockerfile perfectly but I do:
docker logs -f name
and show next error:
/usr/local/bin/docker-entrypoint-sh line 340: exec: npm not found
And, I think that mongodb doesnt run
Why doesnt recognize npm if I add node?
How can run npm and launch mongo?
I'm using ubuntu 17.10
Here is my Dockerfile:
# Install Node
FROM node:latest
# Install Mongo
FROM mongo:4.0.0-xenial
# Author
MAINTAINER MachineGun
# Create user Ubuntu 17.10 (64 bits)
RUN adduser --disabled-login dockeruser
# Work Directory
WORKDIR /home/expressserver
# Copy express project to docker
COPY expressserver expressserver
# Defaul user
USER dockeruser
# Config cointainer PORT:
# MongoDB listening on port: 27017
# Server listening on port: 8080
EXPOSE 27017 8080
# Exec MongoDB
CMD [mongo]
# Exec server with custom npm start
CMD ["npm", "run", "start:dev"]
Also, in app.js I use mongoose with next uri: mongodb://localhost:27017/ExpressServer, its ok?
mongoose.connection.openUri('mongodb://localhost:27017/ExpressServer', { useNewUrlParser: true }, (err, res) => {
if (err) {
console.log('Error: Database not running on port 27017: \x1b[31m%s\x1b[0m', 'offline');
// console.log('throw err: ', err);
throw err;
}
console.log('Database running on port 27017: \x1b[32m%s\x1b[0m', 'online');
});
I've solved the problem :D
Thanks a lot :D
Finally I used docker compose...
Here is my docker-compose.yml:
version: '2'
services:
server:
container_name: expressserver
build: ./
ports:
- "8080:8080"
links:
- mongo
mongo:
container_name: mongoDB
image: mongo:latest
volumes:
- /var/lib/mongodb:/data/db
ports:
- "27017:27017"
command: mongod --port 27017
Here is my Dockerfile:
FROM node:carbon
MAINTAINER MachineGun
RUN adduser --disabled-login dockeruser
WORKDIR /home/dockeruser
COPY expressserver expressserver
WORKDIR /home/dockeruser/expressserver
RUN npm install
USER dockeruser
EXPOSE 8080 27017
CMD ["npm", "start"]
And in my app.js to connect with mongoose:
const options = {
autoIndex: false, // Don't build indexes
reconnectTries: 30, // Retry up to 30 times
reconnectInterval: 500, // Reconnect every 500ms
poolSize: 10, // Maintain up to 10 socket connections
// If not connected, return errors immediately rather than waiting for reconnect
bufferMaxEntries: 0
};
// Database connection
const connectWithRetry = () => {
mongoose.connect("mongodb://mongo/expressdb", options)
.then(()=>{
console.log('Database running on port 27017: \x1b[32m%s\x1b[0m', 'online')
})
.catch( (err) => {
console.log('MongoDB connection unsuccessful on port 27017: \x1b[31m%s\x1b[0m', 'offline');
console.log('Retry after 5 seconds.');
setTimeout(connectWithRetry, 5000)
});
}
connectWithRetry();
Related
I greatly appreciate your effort and the time to solve unresponsive hot-reload function when trying to run Vue.js app on Docker container using Docker engine on Windows 10 while WSL2 active, please take a look at below configurations:
Vue.Setup.Dockerfile
FROM node:17-alpine
EXPOSE 8080
WORKDIR /app/frontend
RUN npm --force install -g #vue/cli#4.5.15
COPY /frontend /app/frontend
ENV PATH /app/frontend/node_modules/.bin:$PATH
CMD [ "npm", "run", "serve" ]
docker-compose.yml
version: "3.8"
services:
vue:
build:
context: .
dockerfile: dockerfiles/Vue.Setup.Dockerfile
restart: always
ports:
- "127.0.0.1:8080:8080"
container_name: vue_ui
volumes:
- ./frontend/:/app/frontend/
- /app/frontend/node_modules
environment:
- CHOKIDAR_USEPOLLING=true
vue.config.js
module.exports = {
publicPath:
process.env.NODE_ENV === "production"
? "/static/dist/"
: "http://127.0.0.1:8080",
pages: {
index: {
entry: 'src/main.js',
template: 'public/index.html',
filename: 'index.html',
title: 'QuestionTime',
chunks: ['chunk-vendors', 'chunk-common', 'index']
},
},
// Webpack configuration
devServer: {
host: "0.0.0.0",
port: "8080",
hot: true,
headers: {"Access-Control-Allow-Origin": "*"},
devMiddleware: {
publicPath: "http://127.0.0.1:8080",
writeToDisk: (filePath) => filePath.endsWith("index.html"),
},
static: {
watch: {
ignored: "/node_modules/",
usePolling: true,
},
},
client: {
webSocketURL: {
/* You need to config this option, otherwise the below error will occur
in your browser console when trying to connect to development server
from another Docker container:
WebSocket connection to 'ws://127.0.0.1:<port-number>/ws' failed
*/
hostname: "0.0.0.0",
pathname: "/ws",
port: 8080,
},
},
},
};
Note: When run the command:
docker-compose up
The below message will show:
It seems you are running Vue CLI inside a container.
Since you are using a non-root publicPath, the hot-reload socket
will not be able to infer the correct URL to connect. You should
explicitly specify the URL via devServer.public.
Access the dev server via http://localhost:<your container's
external mapped port>
FYI: the option:
devServer.public
is no longer available in Vue/cli#4 or later versions.
WORKAROUND
solution
Thanks,
I've got a nuxtjs app runnning in a docker container, i'm trying to use the localhost on the nuxt application to connect to an endpoint but unfortunately i get the following
error RROR request to http://0.0.0.0/api/articles failed, reason: connect ECONNREFUSED 0.0.0.0:80
I'm trying to do a fetch in the nuxt config to generate a sitemap from a getcockpit cms.
Here is a snippets of the fetch.
sitemap: {
hostname: `${process.env.BASE_URL}`,
gzip: true,
routes: async () => {
const articles = await fetch(`http://0.0.0.0/api/articles`, {
method: 'post',
body: JSON.stringify({
filter: {
Published: true
}
})
})
.then((res) => res.json())
.then((values) => {
const results = values.entries
return results
.filter((result) => result.url.length > 0)
.map((result) => result.url)
})
.catch((err) => console.error(err))
return articles
}
},
And a copy of Docker File
FROM node:12.16.1-alpine
# create destination directory
RUN mkdir -p /usr/src/nuxt-app
WORKDIR /usr/src/nuxt-app
# update and install dependency
RUN apk update && apk upgrade
RUN apk add git
# copy the app, note .dockerignore
COPY . /usr/src/nuxt-app/
RUN npm ci
# build necessary, even if no static files are needed,
# since it builds the server as well
RUN npm run build
# expose 5000 on container
EXPOSE 5000
RUN npm config set https-proxy 127.0.0.1:9000
# set app serving to permissive / assigned
ENV NUXT_HOST=0.0.0.0
# set app port
ENV NUXT_PORT=5000
ENV HOST 0.0.0.0
ENV PORT 5000
ENV HTTP_PROXY http://docker.for.mac.localhost.internal:3128
ENV HTTPS_PROXY https://docker.for.mac.localhost.internal:3128
ENV FTP_PROXY ftp://docker.for.mac.localhost.internal:3128
ENV NO_PROXY http://docker.for.mac.localhost.internal:3128
ENV BASE_URL=http://nuxt
ENV GET_ARTICLES_API_TOKEN=token
ENV GET_ARTICLES_URL=example.com
# start the app
CMD [ "npm", "start"]
Current Docker Compose
version: "2"
services:
nuxt:
build: .
ports:
- 5000:5000
environment:
ENV NUXT_HOST: 0.0.0.0
ENV NUXT_PORT: 5000
Have you tried visiting localhost:5000 on your browser?
The default port for http connections is 80 and your application listens on 5000. So when you trying to connect to 0.0.0.0:80, where nothing is listening, the connection is refused.
I've been working on this for awhile and can't seem to get a proper docker setup for my dotnet core application. It works fine when running with dotnet run. Here is my docker file, docker compose file, controller file, and app logs after running docker-compose up.
DockerFile:
# build application
FROM microsoft/dotnet:sdk AS build-env
WORKDIR /app
COPY ./ ./
RUN dotnet restore
RUN dotnet publish -c Release
# run application
FROM microsoft/dotnet:aspnetcore-runtime
WORKDIR /app
COPY --from=build-env app/bin/Release/netcoreapp2.2/publish/ /app
COPY appsettings.json /app
EXPOSE 80
EXPOSE 5000
ENTRYPOINT ["dotnet", "imdb_id_retrieval.dll"]
docker-compose.yml:
version: '3.7'
volumes:
imdb_id_service_volume:
external:
name: imdb_id_service_volume
networks:
app_network:
driver: bridge
services:
postgres_imdb_id_db:
image: postgres
ports:
- "5432:5432"
volumes:
- imdb_id_service_volume:/var/lib/postgresql/data
networks:
- app_network
docker_imdb_id_service:
image: docker_retrieve_data
depends_on:
- "postgres_imdb_id_db"
restart: always
environment:
- ASPNETCORE_ENVIRONMENT=development
build:
context: .
dockerfile: Dockerfile
networks:
- app_network
ports:
- "5000:80"
Controller:
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using imdb_data_retrieval.Logic;
namespace imdb_data_retrieval.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ImdbIdController : ControllerBase
{
private IRetrieveImdbIdService _retrieveImdbIdService;
public ImdbIdController(IRetrieveImdbIdService retrieveImdbIdService){
_retrieveImdbIdService = retrieveImdbIdService;
}
// GET api/values
[HttpGet]
public async Task<ActionResult<string>> Get(string title, string releaseYear)
{
var imdbId = await _retrieveImdbIdService.ScrapeImdbIdAsync(title, releaseYear);
if (imdbId == Constants.InvalidYearResponse)
return BadRequest(Constants.InvalidYearResponse);
if (imdbId == null)
return NotFound(Constants.MovieWasNotFoundResponse);
return Ok(imdbId);
}
}
}
So at this point I run "docker-compose build" and then "docker-compose up". This is the output:
[user#user-pc imdb_id_retrieval]$ docker-compose up
Starting imdb_id_retrieval_postgres_imdb_id_db_1 ... done
Recreating imdb_id_retrieval_docker_imdb_id_service_1 ... done
Attaching to imdb_id_retrieval_postgres_imdb_id_db_1, imdb_id_retrieval_docker_imdb_id_service_1
postgres_imdb_id_db_1 | 2019-05-12 12:37:58.035 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
postgres_imdb_id_db_1 | 2019-05-12 12:37:58.035 UTC [1] LOG: listening on IPv6 address "::", port 5432
postgres_imdb_id_db_1 | 2019-05-12 12:37:58.112 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres_imdb_id_db_1 | 2019-05-12 12:37:58.267 UTC [23] LOG: database system was shut down at 2019-05-12 12:37:12 UTC
postgres_imdb_id_db_1 | 2019-05-12 12:37:58.555 UTC [1] LOG: database system is ready to accept connections
docker_imdb_id_service_1 | derp
docker_imdb_id_service_1 | host=postgres_imdb_id_db; Username=postgres; Port=5432; Database=ImdbIds;
docker_imdb_id_service_1 | warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
docker_imdb_id_service_1 | No XML encryptor configured. Key {964dd0aa-58de-4714-b544-3c48e2b80bb9} may be persisted to storage in unencrypted form.
docker_imdb_id_service_1 | Hosting environment: development
docker_imdb_id_service_1 | Content root path: /app
docker_imdb_id_service_1 | Now listening on: http://[::]:80
docker_imdb_id_service_1 | Application started. Press Ctrl+C to shut down.
Now I go to my browser and go to "http://localhost:5000/api/imdbid?title=iron%20man&releaseYear=2008" and I get a 404 response. The first time I try to hit the endpoint I see
docker_imdb_id_service_1 | warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3]
docker_imdb_id_service_1 | Failed to determine the https port for redirect.
And then no logs on consecutive hits. I don't think I need https configured.
Any ideas on what I'm doing wrong?
EDIT:
My Dockerfile now looks likes this.
# build application
FROM microsoft/dotnet:sdk AS build-env
WORKDIR /app
COPY ./ ./
RUN dotnet restore
RUN dotnet publish -c Release
# run application
FROM microsoft/dotnet:aspnetcore-runtime
WORKDIR /app
COPY --from=build-env app/bin/Release/netcoreapp2.2/publish/ /app
COPY appsettings.json /app
EXPOSE 80
EXPOSE 5000
# changed this
ENTRYPOINT ["dotnet", "imdb_id_retrieval.dll", "--urls", "http://0.0.0.0:5000"]
I have specified port-mapping in docker-compose, but it is still not working, i still have to access site using the port no specified in expose
below is my docker-compose.yml
version: '2'
networks:
default:
external:
name: nat
services:
website:
build:
context: '.'
dockerfile: "./iis.dockerfile"
ports:
- 3000:8081
and the corrosponding dockerfile
FROM microsoft/iis
RUN ["powershell.exe", "Install-WindowsFeature NET-Framework-45-ASPNET"]
RUN ["powershell.exe", "Install-WindowsFeature Web-Asp-Net45"]
ADD www/ c:\\webapp
EXPOSE 8081
RUN powershell New-Website -Name 'web-app' -Port 8081 -PhysicalPath 'c:\webapp' -ApplicationPool '.NET v4.5'
I have to access app using: http://192.168.105.33:8081/, if I do it using port 3000 it does not work.
Is there anything missing in my above configuration?? OS: windows server 2016, using windows containers with hyper-v and docker-compose up -d to get containers up and running...
docker-compose inspect gives me below output
"Ports": {
"8081/tcp": [
{
"HostIp": "0.0.0.0",
"HostPort": "3000"
}
]
},
docker ps gives me below output
eb7aa1e74b7f website_website "C:\\ServiceMonitor..." 14 minutes ago Up 14 minutes 0.0.0.0:3000->
8081/tcp website_website_1
dokcer-compose ps gives me below output
Name Command State Ports
--------------------------------------------------------------------------------
website_website_1 C:\ServiceMonitor.exe w3svc Up 0.0.0.0:3000->8081/tcp
So I should be able to access it on host using port 3000.
Maybe you're launching your container with docker-compose run? There is a difference in port mapping between docker-compose run and docker-compose up [-d] [service] In this case the port configuration will be ignored by design
You can use --service-ports flag or manually expose them using -p flag
I have 2 docker containers managed with docker-compose and can't seem to properly use webpack to proxy some request to the backend api.
docker-compose.yml :
version: '2'
services:
web:
build:
context: ./frontend
ports:
- "80:8080"
volumes:
- ./frontend:/16AGR/frontend:rw
links:
- back:back
back:
build:
context: ./backend
expose:
- "8080"
ports:
- "8081:8080"
volumes:
- ./backend:/16AGR/backend:rw
the service web is a simple react application served by a webpack-dev-server.
the service back is a node application.
I have no problem to access either app from my host :
$ curl localhost
> index.html
$ curl localhost:8081
> Hello World
I can also ping and curl the back service from the web container :
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
73ebfef9b250 16agr_web "npm run start" 37 hours ago Up 13 seconds 0.0.0.0:80->8080/tcp 16agr_web_1
a421fc24f8d9 16agr_back "npm start" 37 hours ago Up 15 seconds 0.0.0.0:8081->8080/tcp 16agr_back_1
$ docker exec -it 73e bash
$ root#73ebfef9b250:/16AGR/frontend# curl back:8080
Hello world
However i have a problem with the proxy.
Webpack is started with
webpack-dev-server --display-reasons --display-error-details --history-api-fallback --progress --colors -d --hot --inline --host=0.0.0.0 --port 8080
and the config file is
frontend/webpack.config.js :
var webpack = require('webpack');
var config = module.exports = {
...
devServer: {
//redirect api calls to backend server
proxy: {
'/api': {
target: "back:8080",
secure: false
}
}
}
...
}
When i try to request /api/test with a link in my app for exemple i get a generic error, the link and google did not help much :(
[HPM] Error occurred while trying to proxy request /api/test from localhost to back:8080 (EINVAL) (https://nodejs.org/api/errors.html#errors_common_system_errors)
I suspect some weird thing because the proxy is on the container and the request is on localhost but I don't really have an idea to solve this.
I think I managed to tacle the problem.
Just had to change the webpack configuration with the following
devServer: {
//redirect api calls to backend server
proxy: {
'/api': {
target: {
host: "back",
protocol: 'http:',
port: 8080
},
ignorePath: true,
changeOrigin: true,
secure: false
}
}
}