获取http:// backend / api / countries net :: ERR_NAME_NOT_RESOLVED

时间:2018-03-21 06:56:13

标签: docker docker-compose docker-link

在向后端进行CORS调用时,我实际上遇到错误:

  

获取http://backend/api/countries net :: ERR_NAME_NOT_RESOLVED

我正在使用这个docker-compose:

搬运工-compose.yml

version: '2'

networks:
  minn_net:

services:

  backend:
    build: backend-symfony
    container_name: backend
    networks:
      - minn_net
    ports:
      - 81:80
    volumes:
      - ./backend-symfony/backend/var/logs-nginx:/var/log/nginx
      - ./backend-symfony/backend/:/var/www/html
      - ./backend-symfony/errors/:/var/www/errors

  db:
    image: mysql:5.7.19
    container_name: db
    networks:
        - minn_net
    ports:
      - 3306
    volumes:
      - "./.data/db:/var/lib/mysql"
    environment:
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
      MYSQL_DATABASE: ${MYSQL_DATABASE}
      MYSQL_USER: ${MYSQL_USER}
      MYSQL_PASSWORD: ${MYSQL_PASSWORD}

  phpmyadmin:
    image: phpmyadmin/phpmyadmin:edge-4.7
    container_name: phpmyadmin
    networks:
      - minn_net
    ports:
      - 8080:80
    links:
      - db

  frontend:
    build: frontend-angular
    container_name: frontend
    networks:
      - minn_net
    links:
      - backend     # I added links as extra: may be the frontend recognises the backend
    ports:
      - 88:80
    volumes:
      - ./frontend-angular/frontend2/dist:/var/www/frontend
      - ./frontend-angular/conf/docker/default.conf:/etc/nginx/conf.d/default.conf
      - ./frontend-angular/logs/nginx/:/var/log/nginx

后端的nginx配置

server {
    listen   80; ## listen for ipv4; this line is default and implied
    listen   [::]:80 default ipv6only=on; ## listen for ipv6

    root /var/www/html/public;
    index index.php;

    # Make site accessible from http://localhost/
    server_name _;

    # Disable sendfile as per https://docs.vagrantup.com/v2/synced-folders/virtualbox.html
    sendfile off;

    # Add stdout logging
    error_log /dev/stdout info;
    access_log /dev/stdout;

        # Add option for x-forward-for (real ip when behind elb)
        #real_ip_header X-Forwarded-For;
        #set_real_ip_from 172.16.0.0/12;

        location / {

            # Match host using a hostname if you like
            #if ($http_origin ~* (https?://.*\.tarunlalwani\.com(:[0-9]+)?$)) {
            #   set $cors "1";
            #}
            set $cors "1";

            # OPTIONS indicates a CORS pre-flight request
            if ($request_method = 'OPTIONS') {
               set $cors "${cors}o";
            }


            # OPTIONS (pre-flight) request from allowed
            # CORS domain. return response directly
            if ($cors = "1o") {
                add_header 'Access-Control-Allow-Origin' '$http_origin' always;
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE, PATCH' always;
                add_header 'Access-Control-Allow-Credentials' 'true' always;
                add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Lang, Authorization' always;
                add_header Content-Length 0;
                add_header Content-Type text/plain;
                return 204;
            }

            add_header 'Access-Control-Allow-Headers' 'Content-Type,Authorization,Lang';
            # add_header 'Access-Control-Allow-Headers' '*';
            add_header 'Access-Control-Allow-Methods' 'POST,GET,PUT,DELETE,OPTIONS';
            add_header 'Access-Control-Allow-Origin' '*';
            try_files $uri /index.php$is_args$args;

        }

        location ~* \.(jpg|jpeg|gif|css|png|js|ico|html|eof|woff|ttf)$ {
            add_header 'Access-Control-Allow-Headers' 'Content-Type,Authorization,Lang';
            #add_header 'Access-Control-Allow-Headers' '*';
            add_header 'Access-Control-Allow-Methods' 'POST,GET,PUT,DELETE,OPTIONS';
            add_header 'Access-Control-Allow-Origin' '*';

            if (-f $request_filename) {
                expires 30d;
                access_log off;
            }
        }

        location ~ \.php$ {
            add_header 'Access-Control-Allow-Headers' 'Content-Type,Authorization,Lang';
            #add_header 'Access-Control-Allow-Headers' '*';
            add_header 'Access-Control-Allow-Methods' 'POST,GET,PUT,DELETE,OPTIONS';
            add_header 'Access-Control-Allow-Origin' '*';
            fastcgi_pass unix:/var/run/php-fpm.sock;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
}

调用后端的角色服务

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
// import { HttpClientModule } from '@angular/common/http';

// Grab everything with import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import { Observer } from 'rxjs/Observer';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

import * as _ from 'lodash';

import { ICountry } from '@app/shared/interfaces';

@Injectable()
export class DataService {

  baseUrl = 'http://backend/api';      // it does not work
  // baseUrl = 'http://172.18.0.4/api'; // it works perfectly

  constructor(private http: HttpClient) { }
  // private httpheadersGet = new HttpHeaders().set("Access-Control-Allow-Origin", "http://localhost:4200");

  public getCountries(): Observable<ICountry[]> {
    return (
      this.http
        .get<ICountry[]>(this.baseUrl + '/countries'/* , {"headers": this.httpheadersGet} */)
        .do(console.log)
        .map(data => _.values(data["hydra:member"]))
        .catch(this.handleError)
    );
  }

}

请注意,如果我从前端手动设置后端IP地址(可以在角度代码中看到),则CORS调用工作正常。那么,我在docker-compose.yml文件的配置中遗漏了什么吗?

PS:甚至指定了网络和容器名称,以避免角度代码中的容器名称不正确。

前端容器的Nginx Dockerfile

FROM debian:stretch-slim

LABEL maintainer="NGINX Docker Maintainers <docker-maint@nginx.com>"

ENV NGINX_VERSION 1.13.9-1~stretch
ENV NJS_VERSION   1.13.9.0.1.15-1~stretch

RUN set -x \
    && apt-get update \
    && apt-get install --no-install-recommends --no-install-suggests -y gnupg1 apt-transport-https ca-certificates \
    && \
    NGINX_GPGKEY=573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62; \
    found=''; \
    for server in \
        ha.pool.sks-keyservers.net \
        hkp://keyserver.ubuntu.com:80 \
        hkp://p80.pool.sks-keyservers.net:80 \
        pgp.mit.edu \
    ; do \
        echo "Fetching GPG key $NGINX_GPGKEY from $server"; \
        apt-key adv --keyserver "$server" --keyserver-options timeout=10 --recv-keys "$NGINX_GPGKEY" && found=yes && break; \
    done; \
    test -z "$found" && echo >&2 "error: failed to fetch GPG key $NGINX_GPGKEY" && exit 1; \
    apt-get remove --purge --auto-remove -y gnupg1 && rm -rf /var/lib/apt/lists/* \
    && dpkgArch="$(dpkg --print-architecture)" \
    && nginxPackages=" \
        nginx=${NGINX_VERSION} \
        nginx-module-xslt=${NGINX_VERSION} \
        nginx-module-geoip=${NGINX_VERSION} \
        nginx-module-image-filter=${NGINX_VERSION} \
        nginx-module-njs=${NJS_VERSION} \
    " \
    && case "$dpkgArch" in \
        amd64|i386) \
# arches officialy built by upstream
            echo "deb https://nginx.org/packages/mainline/debian/ stretch nginx" >> /etc/apt/sources.list.d/nginx.list \
            && apt-get update \
            ;; \
        *) \
# we're on an architecture upstream doesn't officially build for
# let's build binaries from the published source packages
            echo "deb-src https://nginx.org/packages/mainline/debian/ stretch nginx" >> /etc/apt/sources.list.d/nginx.list \
            \
# new directory for storing sources and .deb files
            && tempDir="$(mktemp -d)" \
            && chmod 777 "$tempDir" \
# (777 to ensure APT's "_apt" user can access it too)
            \
# save list of currently-installed packages so build dependencies can be cleanly removed later
            && savedAptMark="$(apt-mark showmanual)" \
            \
# build .deb files from upstream's source packages (which are verified by apt-get)
            && apt-get update \
            && apt-get build-dep -y $nginxPackages \
            && ( \
                cd "$tempDir" \
                && DEB_BUILD_OPTIONS="nocheck parallel=$(nproc)" \
                    apt-get source --compile $nginxPackages \
            ) \
# we don't remove APT lists here because they get re-downloaded and removed later
            \
# reset apt-mark's "manual" list so that "purge --auto-remove" will remove all build dependencies
# (which is done after we install the built packages so we don't have to redownload any overlapping dependencies)
            && apt-mark showmanual | xargs apt-mark auto > /dev/null \
            && { [ -z "$savedAptMark" ] || apt-mark manual $savedAptMark; } \
            \
# create a temporary local APT repo to install from (so that dependency resolution can be handled by APT, as it should be)
            && ls -lAFh "$tempDir" \
            && ( cd "$tempDir" && dpkg-scanpackages . > Packages ) \
            && grep '^Package: ' "$tempDir/Packages" \
            && echo "deb [ trusted=yes ] file://$tempDir ./" > /etc/apt/sources.list.d/temp.list \
# work around the following APT issue by using "Acquire::GzipIndexes=false" (overriding "/etc/apt/apt.conf.d/docker-gzip-indexes")
#   Could not open file /var/lib/apt/lists/partial/_tmp_tmp.ODWljpQfkE_._Packages - open (13: Permission denied)
#   ...
#   E: Failed to fetch store:/var/lib/apt/lists/partial/_tmp_tmp.ODWljpQfkE_._Packages  Could not open file /var/lib/apt/lists/partial/_tmp_tmp.ODWljpQfkE_._Packages - open (13: Permission denied)
            && apt-get -o Acquire::GzipIndexes=false update \
            ;; \
    esac \
    \
    && apt-get install --no-install-recommends --no-install-suggests -y \
                        $nginxPackages \
                        gettext-base \
    && apt-get remove --purge --auto-remove -y apt-transport-https ca-certificates && rm -rf /var/lib/apt/lists/* /etc/apt/sources.list.d/nginx.list \
    \
# if we have leftovers from building, let's purge them (including extra, unnecessary build deps)
    && if [ -n "$tempDir" ]; then \
        apt-get purge -y --auto-remove \
        && rm -rf "$tempDir" /etc/apt/sources.list.d/temp.list; \
    fi

# forward request and error logs to docker log collector
RUN ln -sf /dev/stdout /var/log/nginx/access.log \
    && ln -sf /dev/stderr /var/log/nginx/error.log

EXPOSE 80

STOPSIGNAL SIGTERM

CMD ["nginx", "-g", "daemon off;"]

安装dnsutils

之后
root@123e38093010:/# nslookup backend
Server:     127.0.0.11
Address:    127.0.0.11#53

Non-authoritative answer:
Name:   backend
Address: 172.18.0.3

0 个答案:

没有答案