curl fails when ran inside script

1.2k views Asked by At

Trying to communicate with a running docker container by running a simple curl:

curl -v -s -X POST http://localhost:4873/_session -d \'name=some\&password=thing\'

Which works fine from any shell (login/interactive), but miserably fails when doing it in a script:

temp=$(curl -v -s -X POST http://localhost:4873/_session -d \'name=some\&password=thing\')
echo $temp

With error output suggesting a connection reset:

*   Trying 127.0.0.1:4873...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 4873 (#0)
> POST /_session HTTP/1.1
> Host: localhost:4873
> User-Agent: curl/7.68.0
> Accept: */*
> Content-Length: 29
> Content-Type: application/x-www-form-urlencoded
> 
} [29 bytes data]
* upload completely sent off: 29 out of 29 bytes
* Recv failure: Connection reset by peer <-- this! why?
* Closing connection 0

I'm lost and any hint is appreciated.

PS: tried without subshell and same happens so it's something with the script or the way it's executed.

Edit 1 Added docker compose file. I don't see why regular shell works, but script does not. Note that script is not ran inside docker, it's also running from host.

version: "2.1"
services:
  verdaccio:
    image: verdaccio/verdaccio:4
    container_name: verdaccio-docker-local-storage-vol
    ports:
      - "4873:4873"
    volumes:
      - "./storage:/verdaccio/storage"
      - "./conf:/verdaccio/conf"
volumes:
  verdaccio:
    driver: local

Edit 2 So doing temp=$(curl -v -s http://www.google.com) works fine in the script. It's some kind of networking issue, but I still haven't managed to figure out why.

Edit 3 Lots of people suggested to reformat the payload data, but even without a payload same error is thrown. Also note I'm on Linux so not sure if there are any permissions that can play a role here.

2

There are 2 answers

0
Farhaan Shaik On

if you are using bash script, Can you update the script with below change and try to run again.

address="http://127.0.0.1:4873/_session"
cred="{\"name\":\"some\", \"password\":\"thing\"}"    
temp="curl -v -s -X POST $address -d $cred"
echo $temp

I suspect the issue is within the script and not with docker.

2
seymour On

If you run your container in default mode, docker daemon will locate it in another network, so 'localhost' of your host machine and that one of your container are different. If you want to see the host machine ports from your container, try to run it with key --network="host" (detailed description can be found here)