Deploying Nuxt with Docker, env variables not registering and unexpect API call? Deploying Nuxt with Docker, env variables not registering and unexpect API call? docker docker

Deploying Nuxt with Docker, env variables not registering and unexpect API call?


As you are working in SPA mode, you need your environment variables to be available during build time.

The $ docker run command is therefore already too late to define these variables, and that is what you are doing with your docker-compose's 'environment' key.

So what you need to do to make these variables available during buildtime is to define them in your Dockerfile with ENV PUBLIC_API_URL http://localhost:9061. However, if you want them to be defined by your docker-compose, you need to pass them as build args. I.e. in your docker-compose :

nuxt:  build:    # ...    args:      PUBLIC_API_URL: http://localhost:9061

and in your Dockerfile, you catch that arg and pass it to your build environment like so :

ARG PUBLIC_API_URLENV PUBLIC_API_URL ${PUBLIC_API_URL}

If you don't want to define the variable's value directly in your docker-compose, but rather use locally (i.e. on the machine you're lauching the docker-compose command) defined environment variables (for instance with shell $ export PUBLIC_API_URL=http://localhost:9061), you can reference it as you would in a subsequent shell command, so your docker-compose ends up like this :

nuxt:  build:    # ...    args:      PUBLIC_API_URL: ${PUBLIC_API_URL}


The Nuxt RuntimeConfig properties can be used instead of the env configuration:

https://nuxtjs.org/docs/2.x/directory-structure/nuxt-config#publicruntimeconfig

publicRuntimeConfig is available as $config for client and server side and can contain runtime environment variables by configuring it in nuxt.config.js:

export default {  ...  publicRuntimeConfig: {    myEnv: process.env.MYENV || 'my-default-value',  },  ...}

Use it in your components like so:

// within <template>{{ $config.myEnv }}// within <script>this.$config.myEnv

See also this blog post for further information.