Problem using curl to access a container port inside a DinD runner

My GitLab runner is set up to use DinD, with privileged = true.

My CI job is set up to build and run a docker container, and then hit a port on that container with curl.

However, no matter how I try, curl gives me Connection refused.

Here are relevant excerpts of my .gitlab-ci.yml:

image: "docker:git"
services:
- docker:dind

before_script:
  - apk add curl

build_test:
  script:
    - docker build -t my.docker.repos/myapp:latest .
    - docker run -d --name myapp -p 8000:8000 my.docker.repos/myapp:latest
    - sleep 15
    - curl http://localhost:8000
    - docker rm -f myapp
    

I have tried replacing localhost (in the curl command) with docker and 0.0.0.0. I have tried changing the services bit at the top to:

services:
  - name: docker:dind
    alias: localhost

(Both of these suggestions are from here, btw.)

Neither of those worked.

Do I need to add something special to my docker run command? Like a --link flag or a --network flag?

Does anyone know the answer to this?

This is the last barrier to having gitlab CI working as a CI platform for my organization, and being able to migrate from another CI platform.

(Yes, I am positive that the container exposes port 8000; this curl command works fine outside Gitlab CI).

I also had the same problem, for me the solution was to find the ip of the container that runs my api

build_test:
  script:
  - docker build -t my.docker.repos/myapp:latest .
  - docker run -d --name myapp -p 8000:8000 my.docker.repos/myapp:latest
  - CONTAINER_IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAdress}}{{end}}' myapp) // Replace myapp with your container name.
  - sleep 15
  - curl $CONTAINER_IP:8000
  - docker rm -f myapp

Hope it helps