Search code examples
angularcloud-foundrypcf

How to deploy Angular application on Cloud Foundry using route with path like http://myapp/mycontextpath?


I'm trying to deploy my Angular (6) application on CloudFoundry. I want to map my app on a route like http://myapp.domain.com/mycontextpath , so WITH A PATH. To do so, I deploy my app (CF PUSH) using a yml file like:

---
[...]
buildpack: https://github.com/cloudfoundry/staticfile-buildpack.git
applications:
- name: myangularapp
  routes:
    - route: myapp.domain.com/mycontextpath

In fact, I try multiples things like building my app with or without --base-href parameter like.

ng build --prod --stats-json --base-href /mycontextpath/

OR

ng build --prod --stats-json

I always have a 404 not found result. Everything is working well if I deploy app on a route wihtout path (and without angular --base-href). I also try to add Staticfile file with pushstate: enabled content but in that case, my index.html is always returned.

Thanks for help


Solution

  • Indeed, you need a contextpath folder in your final artifact, and the base-href option at build time. But if you want pushstate, you need some extra steps (see below)

    So, the full answer would be :

    1) Add base-href option to build command :

    ng build --prod --base-href /mycontextpath/
    

    2) Add an extra folder corresponding to mycontextpath (almost done from Angular 6):

    {
      [...]
      "projects": {
        "myangularapp": {
          [...]
          "architect": {
            "build": {
              [...]
              "options": {
                "outputPath": "dist/mycontextpath",
      [...]
    

    3) Set the route in your manifest file :

    ---
    [...]
    buildpack: https://github.com/cloudfoundry/staticfile-buildpack.git
    applications:
    - name: myangularapp
      routes:
        - route: myapp.domain.com/mycontextpath
    

    4) Set your ./Staticfile with :

    root: dist 
    location_include: includes/*.conf
    

    5) Create your custom location config in ./nginx/conf/includes/push_state.conf :

    location /mycontextpath/ {
    
        if (!-e $request_filename) {
          rewrite ^(.*)$ /mycontextpath/ break;
        }
    
        index index.html index.htm Default.htm;
    
    }
    

    6) Push dist folder instead of mycontextpath (that's because location_include property requires custom root). Here is the final structure pushed to CF :

    ./Staticfile
    ./nginx/conf/includes/push_state.conf
    ./dist/mycontextpath/index.html
    ./dist/mycontextpath/main-es2015.543563456.js
    ...
    

    7) Regarding static assets, be sure to use paths relative to base-href :

    <img alt="unicorn" src="./assets/unicorn.png"/>