Why can't I remote debug with Docker/VScode? - docker

I'm trying to remotely debug a Go app using Docker/VScode. My files look like:
main.go
package main
import (
"log"
"net"
"net/http"
"strings"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
message := r.URL.Path
message = strings.TrimPrefix(message, "/")
message = "Hello, " + message + "!"
w.Write([]byte(message))
})
log.Print("starting web server")
listener, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatal(err)
}
log.Printf("Start listening: %v", listener.Addr().String())
if err := http.Serve(listener, nil); err != nil {
log.Fatal(err)
}
}
Dockerfile
FROM golang:1.12
ENV GOPATH /go
ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH
RUN go get github.com/go-delve/delve/cmd/dlv
# set the working directory to /go/src
WORKDIR $GOPATH/src
# Copy everything from the current directory to the working directory inside the container
# (as set by WORKDIR)
COPY . .
# 8080 is for the web application
EXPOSE 8080 2345
docker-compose.yml
version: "3.0"
services:
web:
container_name: go-delve-docker-vscode-example
build: "./"
ports:
- "8080:8080"
- "2345:2345"
security_opt:
- "seccomp:unconfined"
tty: true
stdin_open: true
# command: go run main.go
command: dlv debug --headless --listen=:2345 --api-version=2 --log main.go
launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Delve into Docker",
"type": "go",
"request": "launch",
"mode": "remote",
"remotePath": "/go/src/",
"port": 2345,
"host": "127.0.0.1",
"program": "${workspaceRoot}",
"showLog": true
}
]
}
I can see docker logs for my app, I know it's listening on 2345. But for whatever reason, I can't seem to debug the app. The other issue I'm seeing is, I can't see any logs for trying to run the launch.json.
Edit: I'm running this on Mac OSX, using Docker Desktop.

Docker desktop for Mac runs docker inside a Virtual Machine.
Instead of trying to reach 127.0.0.1:2345, you should use your Virtual machine IP.

Related

deno inspect with docker compose

I am trying to inspect a deno app that is ran inside a docker container with docker-compose.
docker-compose configuration is as follows:
services:
api_bo:
image: denoland/deno:debian-1.23.4
volumes:
- type: bind
source: .
target: /usr/src
ports:
- 9229:9229
- 6005:3000
command: bash -c "cd /usr/src/packages/api_bo && deno task inspect"
depends_on:
- mongo_db
environment:
- MONGO_URL=mongodb://mongo_db:27017/academy_db
- DB_NAME=academy_db
- PORT=3000
deno.json is as follows:
{
"compilerOptions": {
"allowJs": false,
"strict": true
},
"lint": {
"files": {
"include": ["src/"],
"exclude": ["src/types.ts"]
},
"rules": {
"tags": ["recommended"],
"include": [
"ban-untagged-todo",
"no-explicit-any",
"no-implicit-any",
"explicit-function-return-type"
],
"exclude": ["no-debugger", "no-console"]
}
},
"tasks": {
"start": "deno run -A --watch src/app.ts",
"inspect": "deno run -A --inspect src/app.ts"
},
"importMap": "../../import_map.json"
}
Chrome with chrome://inspect does not detect the running process.
When running out of docker with deno run, it works just fine.
It seems that deno only listens to connections from 0.0.0.0 and thus it cannot be inspected using docker port forwarding.
Deno and NodeJS share the same Inspector Protocol from V8, for more see V8 / Docs / Inspector.
And also (lucky) the same parameter "--inspect=[HOST:PORT]" and "--inspect-brk=[HOST:PORT]" so on,
for more see NodeJS / API / Inspect or NodeJS / API / Inspect Brk (THIS is the documentation from NODEJS, so be careful!)
The main "problem" (security reasons) is that NodeJS and Deno Inspector Protocol listen only to localhost / 127.0.0.1 and Docker can't and won't forward these ports. But with the parameter "--inspect" you can change the Host and Port.
Deno CLI
deno run --inspect=0.0.0.0:9229 ./src/my-big-cool-file.ts
Dockerfile
# ...
EXPOSE 9229
# ...
CMD ["run", "--inspect=0.0.0.0:9229", "...", "./src/main.ts"]
TLDR;
your deno.json
//...
"tasks": {
"start": "deno run -A --watch src/app.ts",
"inspect": "deno run -A --inspect=0.0.0.0:9229 src/app.ts"
},
//...
your docker-compose.yml
services:
# ...
api_bo:
# ...
ports:
# THIS IS IMPORTANT, FORWARD DEBUG PROTOCOLS ONLY TO YOUR LOCALHOST! **1
- 127.0.0.1:9229:9229
**1 except: when you need it, and you know what you are doing!!!

Dockerize Vue.js: hot-reload is not working for vue/cli#4.5 or later versions

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,

Next.js API URL problem on Docker container

My problem is:
I made a simple web page with Next.js. I take some content from /pages/api/ endpoints with JSON format and show it in pages and components. Compiling locally (npm run dev or npm run start) is fine. When I run it on Docker on Windows 10, I don't have a problem again. And this is working on Heroku and Vercel. The point I'm having trouble with is: I gave the project to the Devops team and they ran it on Docker. They also directed a domain to this project. But the api endpoints are meaninglessly trying to access an ID URL. When I look from Chrome Devtools it looks like this:
http://013cfdde4910:3000/api/en/brands
I get the following errors as console message.
​Mixed Content: The page at 'https://beta..com/technologies' was loaded over HTTPS, but requested an insecure resource 'http://013cfdde4910:3000/api/en/menu'. This request has been blocked; the content must be served over HTTPS.
Actually it should be http://localhost:3000/api/en/brands. I don't understand where 013cfdde4910 here is coming from and why.
I checked to see if it is among the codes. I looked at the Source of the project that is live, that is, published by the Devops team, from Google Devtools.
_next/static > chunk > pages > _app-eac17e226e00cc01a313.js
When I searched here, I found 013cfdde4910 String in 3 places. Why did it come here when it was built?
For example, the minified code continues as follows.
.... return(0,u.useEffect)((function(){fetch("".concat("http://013cfdde4910:3000","/api/").concat(t.locale,"/) brands")).....
I can see it as localhost in my local build and when I publish it in Windows 10 Docker and look there. So what is causing the localhost -> 013cfdde4910 conversion and how can I solve it?
Dockerfile I use:
FROM node:current-alpine as base
WORKDIR /app
COPY package.json ./
RUN npm install
COPY . .
FROM base AS build
ENV NODE_ENV=production
WORKDIR /build
COPY --from=base /app ./
RUN npm run build
FROM node:current-alpine AS production
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build /build/package*.json ./
COPY --from=build /build/.next ./.next
COPY --from=build /build/public ./public
RUN npm install
EXPOSE 3000
CMD npm run start
I use docker-compose.yml
version: "3"
services:
ui:
container_name: web
restart: always
build:
context: .
dockerfile: Dockerfile
ports:
- "3000:3000"
volumes:
- ./:/app
- /app/node_modules
- /app/.next
env_file:
- .env
And this is next.config.js
module.exports = {
webpackDevMiddleware: (config) => {
config.watchOptions = {
poll: 1000,
aggregateTimeout: 300,
};
return config;
},
async headers() {
return [
{
source: "/api/:path*",
headers: [
{ key: "Access-Control-Allow-Credentials", value: "true" },
{ key: "Access-Control-Allow-Origin", value: "*" },
{
key: "Access-Control-Allow-Methods",
value: "GET,OPTIONS,PATCH,DELETE,POST,PUT",
},
{
key: "Access-Control-Allow-Headers",
value:
"X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version",
},
],
},
];
},
reactStrictMode: true,
generateEtags: false,
i18n: {
locales: ["en", "tr"],
defaultLocale: "en",
localeDetection: false,
},
env: {
VERSION: process.env.VERSION,
MODE: process.env.MODE,
APP_NAME: process.env.APP_NAME,
HOST: process.env.HOST,
HOSTNAME: process.env.HOSTNAME,
PORT: process.env.PORT,
GA_TRACKING_ID: process.env.GA_TRACKING_ID,
},
generateBuildId: async () => {
return new Date().toDateString();
},
eslint: {
ignoreDuringBuilds: false,
},
};
Thanks for posting the config, it appears the hostname is grabbed as the docker container ID - You do not post the actual fetch code but my guess is - this environment variable is used.
`HOSTNAME: process.env.HOSTNAME`
It is either passed as a environment variable or interpreted to be the container ID, you need a way to create a domain:3000/api/brands which could be part of the Docker deploy, maybe a nginx proxy.

In VSCode, 'Python: Remote Attach' fails to connect to a running Docker Container

Good evening,
I have a container which is running and ready to connect. In VSCode I've tried to 'Attach Visual Studio Code' to open a new Dev Container, select the sources, hoping I can debug.
I'm unable to select breakpoints and the code isn't running.
Nothing happens.
I've also tried 'Python: Attach Remote'.
Nothing happens and there's no errors.
Launch.json:
{
"name": "Python: Remote Attach",
"type": "python",
"request": "attach",
"connect": {
"host": "0.0.0.0",
"port": 3000
},
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "."
},
]
}
Docker Compose.yml
services:
sfunc:
image: sfunc
build:
context: .
dockerfile: ./Dockerfile
command: ["sh", "-c", "pip install debugpy -t /tmp && python /tmp/debugpy --log-to-stderr --wait-for-client --listen 127.0.0.1:3000 home/site/wwwroot/TimerTrigger/__init__.py "]
ports:
- 3000:3000
How could I troubleshoot this ?
Thank you
Those hostnames didn't work for me. Using localhost in the launch.json and 0.0.0.0 as the host in the --listen option worked.

express js middleware not getting connected using docker-compose

I am relatively new to nextjs and react space of development, trying my hand over this, please pardon if anything straight forward and i am not seeing it.
So i am trying to call some API which gives some data which i want to render on UI. So far on local it was giving corrs issue so i have added express js middleware to bypass this issue.
Now i want to deploy this app on docker using Dockerfile. So i have got things right and UI compiles successfully but middleware API calls are failing. Below is the Dockerfile, docker-compose file i am using to start the app.
client Dockerfile:
FROM node:latest
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
EXPOSE 3000
CMD [ "npm" , "run", "dev" ]
server Dockerfile
FROM node:latest
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
EXPOSE 5000
CMD [ "npm", "run" , "start" ]
docker-compose file
version: "3"
services:
frontend:
container_name: awesome_web
build:
context: ./
dockerfile: Dockerfile
image: apaliwal/awesome_web
ports:
- "3000:3000"
volumes:
- ./:/usr/src/app
backend:
container_name: awesome_server
build:
context: ./server
dockerfile: Dockerfile
image: apaliwal/awesome_server
ports:
- "8080:8080"
volumes:
- ./server:/usr/src/app
client package.json
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "NODE_TLS_REJECT_UNAUTHORIZED='0' node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"node-fetch": "^2.6.0"
}
}
client package.json
{
"name": "project_name",
"version": "1.0.0",
"main": "pages/index.js",
"private": true,
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
[dependecies]
...
...
...
server.js
const express = require('express');
const http = require('http');
const fetch = require('node-fetch');
const app = express();
const server = http.createServer(app);
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
next();
});
app.get('/issues/:projectID', (req, res) => {
fetch(`[url]`, {
headers: [auth],
compress: false
})
.then(async (response) => {
console.log(response.status);
if(response.status >= 200 && response.status < 400) {
const jsonResponse = await response.text();
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(jsonResponse);
}
})
.catch((err) => {
console.error(err);
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end("Error occurred! Data not found/internal server error");
});
})
server.listen(8080, '127.0.0.1' , err => console.log( err || "Your server is listening on "+'127.0.0.1'+" port "+'8080'));
Please help with this, tried many things exposing port to 8080.
docker-compose up --build does work below are the console logs for it as well, it just in network logs the getting:
(failed)net::ERR_SOCKET_NOT_CONNECTED

Resources