dockergorethinkdb

Error on connecting to rethinkDB from golang


I ran docker container with rethinkdb, then run go file for connecting to database, but I have errors while connecting.

Hi, everyone. I need help with rethinkdb, I ran docker container:

docker run --name rth -p 8100:8080 -d rethinkdb

Then went to http://localhost:8100 and has main page of rethinkdb, so everythink is fine. But when I try to connect to databases from golang I have some errors:

package main

import (  
    r "gopkg.in/rethinkdb/rethinkdb-go.v6"
    "log"
    "fmt"
)

func main() {
    _, err := r.Connect(r.ConnectOpts{
        Address: "localhost:28015",
        Database: "test",
    })
    if err != nil {
        fmt.Println(err)
        log.Fatal("Could not connect")
    }
}

After running go run main.go I have this error:

rethinkdb: dial tcp 127.0.0.1:28015: connect: connection refused
2023/05/18 01:38:39 Could not connect
exit status 1

I thank that this happens because of incorrect port(28015), but if I change it, I have same problem, except port = 8100. If I put 8100 instead of 28015 and have this error:

rethinkdb: Unexpected EOF: HTTP/ 400 Bad Request

2023/05/18 01:38:52 Could not connect
exit status 1

May be someone know how to fix this)


Solution

  • -p 8100:8080 maps port 8080 in the container to port 8100 on your host. You don't map any other ports so, when you attempt to access any port other than 8100 (for example 127.0.0.1:28015), your request will not reach the container. Something else on the host may be listening on the port, or there may be nothing listening.

    You mentioned that you are able to access the admin interface on http://localhost:8100; if you check the logs you will notice something like:

    Listening for administrative HTTP connections on port 8080
    Listening for client driver connections on port 28015
    

    So the server is listening for connections on multiple ports. Port 8080 (which you map to 8100) is the admin HTTP interface and 28015 is for driver connections (this is covered in the docs). Your code is attempting to connect to port 28015 (which is correct) but you are not mapping that port so it's inaccessible on the host; fix this with:

    docker run --name rth -p 8100:8080 -p 28015:28015 -d rethinkdb
    

    This will map port 28015 in the container to port 28015 on the host (you can use a different host port if you want; just remember to update the code). We can now successfully connect with something like:

    package main
    
    import (
        "fmt"
        "log"
    
        r "gopkg.in/rethinkdb/rethinkdb-go.v6"
    )
    
    func main() {
        _, err := r.Connect(r.ConnectOpts{
            Address:  "localhost:28015",
            Database: "test",
        })
        if err != nil {
            fmt.Println(err)
            log.Fatal("Could not connect")
        }
        fmt.Println("Connected")
    }