#nuxt.js docker镜像启动后无法访问
问题背景
nuxt.js项目打包后,制作成docker镜像,映射默认端口3000到3000,启动以后,访问
http://localhost:3000
结果无法访问,这是为什么呢?
解决方法
原来,根据nuxt文档,nuxt服务默认是运行在localhost:3000上,直接在本机运行,是可以正常访问的。
https://nuxtjs.org/docs/2.x/features/configuration#edit-host-and-port
By default, the Nuxt.js development server host is localhost which is only accessible from within the host machine.
但是,制作成docker镜像以后,就只能在容器内部访问了。
修改方法有两种
方法1.修改nuxt.config.js的server.host
在nuxt.config.js文件中,增加以下:
  server: {
    host: '0' // default: localhost
  }
重新制作nuxt镜像,或者映射修改后的nuxt.config文件到容器,重新运行即可。
方法2.在Dockerfile中设置HOST环境变量
添加以下命令
ENV HOST 0.0.0.0
或者在运行容器时,添加环境变量
--env HOST=0
其他
注意,如果不设置host,nuxt也仅限本机访问,在同一个网络里的其他机器也是无法访问的,这与docker容器的情况是一样的。
开发环境想要其他机器可以访问,在不改配置的情况下,可以使用以下命令:
HOST=0 PORT=3000 yarn dev
参考
- https://nuxtjs.org/docs/2.x/features/configuration#edit-host-and-port
 - https://www.nuxtjs.cn/faq/host-port
 - https://segmentfault.com/a/1190000010396645
 - https://github.com/wsdo/docker-nuxt/blob/master/Dockerfile
 
贡献一个nuxt.js的Dockerfile
注意
- 设置srcDir
 
  srcDir: 'src/'
- 本例中,没有复制src到容器里编译,所以在制作镜像前,需要更新.nuxt文件夹,确保最新。
 
yarn build
完整Dockerfile
FROM node:14-alpine
ENV NUXT_VERSION=2.15.7
WORKDIR /app
ADD package.json yarn.lock nuxt.config.js ./
RUN : \
  && yarn install \
  && yarn cache clean \
  && :
# 复制nuxt build文件夹
ADD .nuxt ./.nuxt
# 如果使用了content模块,还需要复制content文件夹
# ADD ./src/content ./src/content
ENTRYPOINT ["npx", "nuxt-start"]
EXPOSE 3000
完整nuxt.config.js
export default {
  srcDir: 'src/',
  // Target: https://go.nuxtjs.dev/config-target
  target: 'server',
  ssr: true, // 是否在服务端渲染,false为在客户端渲染
  server: {
    host: '0',
    port: 3000
  },
  // Global page headers: https://go.nuxtjs.dev/config-head
  head: {
    title: 'xmanyou.com',
    htmlAttrs: {
      lang: 'en'
    },
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: '' },
      { name: 'format-detection', content: 'telephone=no' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },
  // Global CSS: https://go.nuxtjs.dev/config-css
  css: [
  ],
  // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
  plugins: [
  ],
  router: {
    middleware: []
  },
  // Auto import components: https://go.nuxtjs.dev/config-components
  components: true,
  // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
  buildModules: [
    // https://go.nuxtjs.dev/eslint
    '@nuxtjs/eslint-module',
  ],
  // Modules: https://go.nuxtjs.dev/config-modules
  modules: [
    // https://go.nuxtjs.dev/axios
    '@nuxtjs/axios',
    '@nuxt/content'
  ],
  // Axios module configuration: https://go.nuxtjs.dev/config-axios
  axios: {},
  // Build Configuration: https://go.nuxtjs.dev/config-build
  build: {
    transpile: [],
  },
  generate: {
    exclude: [/game/]
  }
}