Search code examples
dockercurldocker-composegitlab-cidocker-in-docker

gitlab-ci.yml & docker-in-docker (dind) & curl returns connection refused on shared runner


I'm trying to create a simple GitLab CI where I spin up a container using docker-compose up then try to access it using curl and finally tear it down using docker-compose down. docker-compose up spins up perfectly fine and I can see the container up using docker ps -a, however when I curl, I get "connection refused".

here is my gitlab-ci.yml

image: docker

services:
 - docker:dind

before_script:
 - apk add --update python py-pip python-dev && pip install docker-compose
 - apk add --update curl && rm -rf /var/cache/apk/*

stages:
 - test

test:
 stage: test
 script:
  - docker-compose up -d
  - docker ps -a
  - curl http://localhost:5000/api/values
  - docker-compose down

here is the runner's logs

Image for service testwebapp was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`.
Creating test-container ... 

Creating test-container ... done
$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                  PORTS                    NAMES
3423adfb1f3b        mytestwebapp        "dotnet TestWebApp.d…"   1 second ago        Up Less than a second   0.0.0.0:5000->5000/tcp   test-container
$ curl http://localhost:5000/api/values
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0curl: (7) Failed to connect to localhost port 5000: Connection refused
ERROR: Job failed: exit code 7

Docker Compose:

version: '3.4'

services:
  testwebapp:
    image: mytestwebapp
    build:
      context: .
      dockerfile: TestWebApp/Dockerfile
    container_name: test-container

Docker compose override:

version: '3.4'

services:
  testwebapp:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - ASPNETCORE_URLS=http://0.0.0.0:5000
    ports:
      - "5000:5000"

Solution

  • Update your gitlab-ci.yml file:

    1. set sleep 15 before running curl. 15 is an arbitrary period in seconds when your service should start exactly.

    2. Next, there are 2 options: https://docs.gitlab.com/ee/ci/services/#how-services-are-linked-to-the-job:

    Option 1: Replace localhost in curl http://localhost:5000/api/values with docker like this curl http://docker:5000/api/values

    Option 2:

    services:
      - name: docker:dind
        alias: localhost