How to expose build step results using docker + Google Cloud Build

I’m trying to build a next.js application on Google Cloud Build in a monorepo using Yarn workspaces. I’ve found that one of our slowest points during the build process is installing node modules since we have to do it in a few different folders. Ideally, I’d like to leverage Docker to handle the caching of node_modules if nothing has changed. My Dockerfile is as follows:

FROM node:10.13
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install -g yarn
RUN yarn
COPY . .

My cloudbuild.yaml is below:

steps:
- name: 'gcr.io/cloud-builders/docker'
  args: [ 'build', '-t', 'gcr.io/$PROJECT_ID/dashboard-modules', './packages/dashboard' ]
- name: node:10.15.1
  entrypoint: yarn
  # `yarn build-dev` relies on the installation of `next` that happens in the previous step
  args: ['--cwd', 'packages/dashboard', 'build-dev']
...

My expected result is that upon first build, COPY package*.json will view the contents of package.json and if nothing has changed, it will keep the same output for node_modules. One very critical step here is that we install next which is used later in the build process to build the app itself from package.json:

"scripts": {
  "build": "next build",
  ...
}

However, when I get to the second step in cloudbuild.yaml, my build errors with env: 'next': No such file or directory.

It seems that I need to somehow “surface” (for lack of a better term) whatever happens in the first step of cloudbuild.yaml and make the next command available to the second step. My question though is how can I do that?

I should note that I’m fairly new to Docker and trying to wrap my head around how it works.

Source: StackOverflow