Search code examples
gitlabcontinuous-integrationpipelinegitlab-ci-runnergitlab-pipelines

Gitlab CI/CD how to catch curl response in pipeline


I have a pipeline which starts some maven/java app, now I want to add a test stage , where I check if the app starts successfully , for example: when the build stage finishes, I check with curl

127.0.0.1:8080 if response 200 ok , else failed.

How can I create a Gitlab pipline for this use case?

stages:
  - build
  - deploy
  - test

build:
  stage: build
  script:
    - echo Build Stage 1
  tags:
    - java-run

deploy:
  stage: deploy
  tags:
    - java-run
  script:
    - "some script"

test:
  stage: test
  tags:
    - java-run
  script:

Solution

  • I'm making some assumptions around your use-case here, so let me know if they aren't right. I'm assuming:

    • You're starting the java app remotely (I.e., your pipeline is deploying it to a cloud provider or non-CI/CD server)
    • Your server running CI/CD has access to the application via the internet

    If so, assuming that you want your job to fail if the service is not accessible, you can simply curl the url using the -f flag, and it will fail if it receives a 404 error. Examples:

    
    test:
      image: alpine:latest
      script:
        - apk add curl
        - curl -o /dev/null -s -w "%{http_code}\n" https://httpstat.us/404 -f
    
    

    The above job will fail, as curl returns exit code 22 when it receives a >= 400 error code and the -f flag is used:

    Job failing

    Now, if you're attempting to run the app in your CI/CD (which is why you're referring to 127.0.0.1 in your question), then you can't run the app locally in one job and test in another. The job would only exist and run within the context of the container that's running it, and test is in a separate container because it's a separate job. You have two options if you're attempting to run your app within the context of CI/CD and test it:

    1. You can run your tests in the same job where you start the app (you may need to run the app using nohup to run it in the background)
    2. You can package your app into a docker container, then run it as a service in your test job.