Skip to content

Specifying socketPath but Dockerode is using HTTP. (bun.js) #747

Open

Description

@alexdotpink

Hi, I'm initializing dockerode like this:

const docker = new Docker({socketPath: '/var/run/docker.sock'});

but when I use it, it gives the following error:

Could not get container information. ConnectionRefused: Unable to connect. Is the computer able to access the url?
path: "http://localhost/containers/b81d1747b4d9/json"

I am using Bun.

Activity

  1. ptrxyz commented on Oct 23, 2023

    @ptrxyz

    An into the same problem ... not sure how that would happen. Maybe a permission thing?

  2. ptrxyz commented on Oct 23, 2023

    @ptrxyz

    Maybe it matters: my Docker daemon version is 1.24, this is my test code:

    import Docker from 'dockerode';
    const docker = new Docker({ socketPath: '/var/run/docker.sock' });

    The error:

    /tmp/dockerode · sudo bun run index.ts
    Error: ConnectionRefused: Unable to connect. Is the computer able to access the url?
     path: "http://localhost/containers/json?all=true"
    

    Debug info:

    /tmp/dockerode · ls -la /var/run/docker.sock
    srw-rw---- 1 root docker 0 Oct 18 16:16 /var/run/docker.sock
    
    /tmp/dockerode · docker info
    Client:
     Version:    24.0.6
     Context:    default
     Debug Mode: false
    
    Server:
     Containers: 0
      Running: 0
      Paused: 0
      Stopped: 0
     Images: 2
     Server Version: 24.0.6
     Storage Driver: overlay2
      Backing Filesystem: extfs
      Supports d_type: true
      Using metacopy: true
      Native Overlay Diff: false
      userxattr: false
     Logging Driver: json-file
     Cgroup Driver: systemd
     Cgroup Version: 2
     Plugins:
      Volume: local
      Network: bridge host ipvlan macvlan null overlay
      Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
     Swarm: inactive
     Runtimes: io.containerd.runc.v2 runc sysbox-runc
     Default Runtime: runc
     Init Binary: docker-init
     containerd version: 8c087663b0233f6e6e2f4515cee61d49f14746a8.m
     runc version: 
     init version: de40ad0
     Security Options:
      seccomp
       Profile: builtin
      cgroupns
     Kernel Version: 6.5.7-zen2-1-zen
     Operating System: Arch Linux
     OSType: linux
     Architecture: x86_64
     CPUs: 8
     Total Memory: 23.26GiB
     Name: nine
     ID: 29c770ff-e2ff-4c97-84e9-1e3da89486ae
     Docker Root Dir: /var/lib/docker
     Debug Mode: false
     Experimental: false
     Insecure Registries:
      127.0.0.0/8
     Live Restore Enabled: false
    
  3. apocas commented on Oct 23, 2023

    @apocas
    Owner

    Investigating

  4. apocas commented on Oct 23, 2023

    @apocas
    Owner

    I can't reproduce that :(
    Tried exactly the same scenario bun and nodejs.

  5. hazelnutcloud commented on Oct 24, 2023

    @hazelnutcloud

    running into same problem. using bun v1.0.7 on mac

  6. hazelnutcloud commented on Oct 24, 2023

    @hazelnutcloud

    This seems to be a problem with bun. See oven-sh/bun#6055

  7. apocas commented on Oct 24, 2023

    @apocas
    Owner

    Now I can reproduce it using bun (forgot mocha was evoking node) :)
    Indeed is seems something related with bun, not much we can do right now.

  8. changed the title [-]Specifying socketPath but Dockerode is using HTTP.[/-] [+]Specifying socketPath but Dockerode is using HTTP. (bun.js)[/+] on Oct 30, 2023
  9. pinned this issue on Oct 30, 2023
  10. recanman commented on Feb 24, 2024

    @recanman

    Temporary solution I'm using:

    Run this command:

    socat TCP-LISTEN:3000,reuseaddr,fork UNIX-CONNECT:/var/run/docker.sock

    Use it like this:

    new Dockerode({protocol: 'http', host: 'localhost', port: 3000})
  11. Anprotaku commented on Mar 6, 2024

    @Anprotaku

    Hello, is there any fix for this issue to get linux socket to work?

  12. recanman commented on Mar 7, 2024

    @recanman

    There is a pull request, but no response yet.

  13. Anprotaku commented on Mar 7, 2024

    @Anprotaku

    @recanman it looks like they merged another pull request that should fix it
    oven-sh/bun#9284

    Should be safe to close this issue

  14. recanman commented on Mar 8, 2024

    @recanman

    Great, thank you!
    Mentioning author: @Fumaz

  15. dionjwa commented on May 21, 2024

    @dionjwa

    I am using dockerode@4.0.2 via deno, and I am still getting this issue.

  16. devingfx commented on Oct 10, 2024

    @devingfx

    Same issue with Deno 1.43.6, dockerode 4.0.2, with:

    import Docker from 'npm:dockerode'
    const docker = new Docker({socketPath: '/var/run/docker.sock'})
    const images = await docker.listImages()
    console.log( images )

    Got:

    error: Uncaught (in promise) TypeError: error sending request for url (http://localhost/images/json): error trying to connect: tcp connect error: Connection refused (os error 111)
        at async node:http:397:21
  17. Karrq commented on Oct 11, 2024

    @Karrq

    I'm also getting the same issue with Deno 2.

    I think it's related due to the fact that it's the same issue as what bun had, and other deno users will be able to find this and not waste time debugging why it's happening

  18. crackedbeefcake commented on Oct 29, 2024

    @crackedbeefcake

    same issue with deno 2. is there an issue yet? couldnt find it if there is

  19. adamazad commented on Dec 18, 2024

    @adamazad

    Same issue with Deno v2.1.4.

  20. DanielSharkov commented on Feb 23, 2025

    @DanielSharkov

    Same issue with Deno 1.43.6, dockerode 4.0.2, with:

    import Docker from 'npm:dockerode'
    const docker = new Docker({socketPath: '/var/run/docker.sock'})
    const images = await docker.listImages()
    console.log( images )
    Got:

    error: Uncaught (in promise) TypeError: error sending request for url (http://localhost/images/json): error trying to connect: tcp connect error: Connection refused (os error 111)
    at async node:http:397:21

    Running this code on Deno 2.2.1 and dockerode 4.0.4 results for me in:

    error: Uncaught (in promise) BadResource: Bad resource ID
        at node:http:327:27
        at ClientRequest._writeHeader (node:http:440:7)
        at ClientRequest._flushHeaders (node:_http_outgoing:382:12)
        at Socket.onConnect (node:http:486:16)
        at Socket.emit (ext:deno_node/_events.mjs:405:35)
        at PipeConnectWrap._afterConnect [as oncomplete] (node:net:159:12)
        at Pipe.afterConnect (ext:deno_node/internal_binding/connection_wrap.ts:43:11)
        at ext:deno_node/internal_binding/pipe_wrap.ts:123:14
        at eventLoopTick (ext:core/01_core.js:177:7)
    

    But fortunately, I found a great workaround for Deno here: denoland/deno#20255 (comment)

    Still, I had to tweak it slightly. The original Promise.all implementation didn't make sense and didn't work for me. Here's my improved version:

    import { copy } from 'jsr:@std/io';
    import { ClientRequest } from 'node:http';
    
    function startDockerProxy(proxyPort = 2375): () => Promise<void> {
    	const originalSocketHandler = ClientRequest.prototype.onSocket;
    	ClientRequest.prototype.onSocket = function (socket) {
    		socket.unref = function () {
    			return this;
    		};
    		return originalSocketHandler.call(this, socket);
    	};
    
    	Deno.env.set('DOCKER_HOST', `tcp://localhost:${proxyPort}`);
    	const tcpListener = Deno.listen({ port: proxyPort });
    	const handleConnections = async () => {
    		for await (const tcpConn of tcpListener) {
    			dockerProxyHandleConnection(tcpConn);
    		}
    	};
    
    	const connectionsHandler = handleConnections();
    	return async () => {
    		tcpListener.close();
    		ClientRequest.prototype.onSocket = originalSocketHandler;
    		await connectionsHandler;
    	};
    }
    
    async function dockerProxyHandleConnection(tcpConn: Deno.Conn) {
    	let unixConn: Deno.Conn | undefined;
    	try {
    		unixConn = await Deno.connect({ transport: 'unix', path: '/var/run/docker.sock' });
    
    		const tcpToUnixPromise = copy(tcpConn, unixConn).catch((err) => {
    			if (err.code !== 'EPIPE' && err.code !== 'EINTR') {
    				console.error('[TCP -> Unix] error:', err);
    			}
    		});
    		const unixToTcpPromise = copy(unixConn, tcpConn).catch((err) => {
    			if (err.code !== 'EPIPE' && err.code !== 'EINTR') {
    				console.error('[Unix -> TCP] error:', err);
    			}
    		});
    		await Promise.race([tcpToUnixPromise, unixToTcpPromise]);
    	} catch (error) {
    		console.error('Docker proxy connection error:', error);
    	} finally {
    		// Extra safety: ensure connections are closed even if something goes wrong above
    		try {
    			unixConn?.close();
    			tcpConn.close();
    		} catch (err) {
    			console.log('FATAL: closing connections failed: ', err);
    		}
    	}
    }

    Then I'm just using it like:

    import { ArangoDBContainer } from '@testcontainers/arangodb';
    import { Database } from 'arangojs';
    
    export async function connectArangoDbContainer(dbName: string) {
    	const stopDockerProxy = startDockerProxy();
    	const arangoDbContainer = await new ArangoDBContainer('arangodb:3.11', '').start();
    
    	const arangoDb = new Database();
    	// ...
    
    	const stopContainer = async () => {
    		await arangoDbContainer.stop();
    		await stopDockerProxy();
    	};
    	return { arangoDbContainer, arangoDb, stopContainer };
    }
    
    const { arangoDb, stopContainer } = connectArangoDbContainer('test');
    // ... do smth
    await stopContainer();

    Make sure to stop both the container and the proxy properly. Don’t just call arangoDbContainer.stop() — use the stop handler to first stop the container and then the proxy, ensuring all listeners are closed.

    I'm on macOS. I don't know if this will work on windows systems.

  21. marcus-sa commented on Mar 28, 2025

    @marcus-sa

    I don't have any issues with Bun version 1.2.5

  22. kravetsone commented on May 26, 2025

    @kravetsone
  23. kravetsone commented on May 26, 2025

    @kravetsone

    oven-sh/bun#18653

    looks like now it windows specific

  24. PssbleTrngle commented on Mar 23, 2026

    @PssbleTrngle

    This is still happening for me with the newest version of bun (1.3.11) and dockerode (4.0.10) on linux.
    Since the bun PR was merged, I don't really understand how this can still be an issue?

     error: Was there a typo in the url or port?
       path: "http://localhost/containers/json",
      errno: 0,
       code: "FailedToOpenSocket"
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions