Gaia Data Release 2 (Gaia DR2) contains results for 1693 million sources in the magnitude range 3 to 21 based on observations collected by the European Space Agency Gaia satellite during the first 22 months of its operational phase. We describe the input data, models, and processing used for the astrometric content of Gaia DR2, and the validation of these results performed within the astrometry task. Some 320 billion centroid positions from the pre-processed astrometric CCD observations were used to estimate the five astrometric parameters (positions, parallaxes, and proper motions) for 1332 million sources, and approximate positions at the reference epoch J2015.5 for an additional 361 million mostly faint sources. Special validation solutions were used to characterise the random and systematic errors in parallax and proper motion. For the sources with five-parameter astrometric solutions, the median uncertainty in parallax and position at the reference epoch J2015.5 is about 0.04 mas for bright (G<14 mag) sources, 0.1 mas at G=17 mag, and 0.7 mas at G=20 mag. In the proper motion components the corresponding uncertainties are 0.05, 0.2, and 1.2 mas/yr, respectively. The optical reference frame defined by Gaia DR2 is aligned with ICRS and is non-rotating with respect to the quasars to within 0.15 mas/yr. From the quasars and validation solutions we estimate that systematics in the parallaxes depending on position, magnitude, and colour are generally below 0.1 mas, but the parallaxes are on the whole too small by about 0.03 mas. Significant spatial correlations of up to 0.04 mas in parallax and 0.07 mas/yr in proper motion are seen on small (<1 deg) and intermediate (20 deg) angular scales. Important statistics and information for the users of the Gaia DR2 astrometry are given in the appendices.